File Uploading in ASP.NET 2.0


This article tells us to upload any file into our system by using FileUpload Control in ASP.NET 2.0.
  1. Add new webform to your project.
  2. Name it as FileUploading.aspx.
  3. Drag and drop FileUpload control from toolbox into webform.
  4. Drag and drop Button control from toolbox into webform. Put Button Text to "Upload".
  5. Double click on the Button Control it generates "Button1_Click" event in .cs file.
  6. And finally drag and drop Label control from toolbox into webform.
Create a folder in D drive with the name "Uploads"

In FileUploading.aspx.cs, write the following code under button double click "Button1_Click" event

protected void Button1_Click(object sender, EventArgs e)
{
    try
    {
        if (FileUpload1.HasFile)
        {
            FileUpload1.SaveAs(@"D:\Uploads\" + FileUpload1.FileName);
            lblFileMsg.Text = "<b>File Uploaded Successfully.</b><br>";
            lblFileMsg.Text += "File Name :" + FileUpload1.FileName;
            lblFileMsg.Text += "<br>File Type :" + FileUpload1.PostedFile.ContentType;
            lblFileMsg.Text += "<br>File Size :" + FileUpload1.PostedFile.ContentLength;
        }
        else lblFileMsg.Text = "Failed to Upload Your File";
    }
    catch (Exception)
    { }
}

By default it uploads up to 4MB size of files. It doesn't allow 'exe' files.

To increase the limit sizes of the file by adding a tag in web.config file. Add this tag in between.

<System.Web>
  <httpRuntime executionTimeout="500" maxRequestLength="4096" />
</System.Web>

Here the executionTimeout in milliseconds and maxRequestLength.

In kb. So, increase the maxRequestLength to upload large files.

Up Next
    Ebook Download
    View all
    Learn
    View all