Upload file to webserver using c#

  1. Place one Label, FileUpload and Button control to your page.
  2. Name Label control as “lblMessage”, FileUpload control as “fuUpload” and Button control as “btnSubmit”
  3. Create a Method as shown below,
    private bool UploadFile()
    {
        bool _Result = false;
        try
        {
          if (fuUpload.HasFile)
          {
              string strFileName = DateTime.Now.ToString("ddMMyyyy_HHmmss");
              string strFileType = System.IO.Path.GetExtension(fuUpload.FileName).ToString().ToLower();
              strFileName += fuUpload.FileName;
              ViewState["FileName"] = strFileName;
              if (strFileType.ToLower() == ".pdf")
              {
                   fuUpload.SaveAs(Server.MapPath("~/Pdf/" + strFileName));
                   _Result = true;
              }
              else
              {
                   lblMessage.Text = "Only pdf files allowed.";
                   _Result = false;
              }
          }
          else
          {
              _Result = false;
              lblMessage.Text = "Please select valid pdf file";
          }
        }
        catch (Exception ex)
        {
             _Result = false;
             lblMessage.Text = ex.Message;
        }
        return _Result;
    }
    
  4. Now under btnSubmit_click event call the created method as shown below
    if (UploadFile())
    {
         // You can get the uploaded file name from below viewstate
         string FileName = Convert.ToString(ViewState["FileName"]);
    }
    
Reference: Muthukumar (http://nadarmuthukumar.blogspot.in)
Hope you liked this and let me know your thoughts on post through your comments :)

0 comments:

Twitter Delicious Facebook Digg Stumbleupon Favorites More