Friday, July 15, 2011

File Upload Control C#

protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
// SaveAs method of PostedFile property used
// to save the file at specified rooted path
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/App_Data") + System.IO.Path.DirectorySeparatorChar + FileUpload1.PostedFile.FileName);

// success message
Label1.Text = "File " + FileUpload1.PostedFile.FileName + " uploaded successfully.";
}
catch (Exception ex)
{
// error message
Label1.Text = "Some problem occurred while uploading the file. Please try after some time.";
}
}
else
{
// warning message
Label1.Text = "Please choose a file to upload.";
}
}
---------------------------------------------

ASP.Net File Upload Example using C# code

Updated on 20 Aug 2010, Published on 30 Oct 2009

In the previous tutorial: ASP.Net FileUpload Control PostedFile property we learnt about its accessible member properties and method. As it provides the object of HttpPostedFile class it points the memory stream of the uploaded file stored in the cache area of server memory. You can access different attributes of the uploaded file using the accessible properties of PostedFile property of FileUpload control. In this tutorial we will use the simplest C# code to learn the very basic steps for uploading file selected from the client’s computer system to the web server location specified in the code.

Apart from FileUpload server control for uploading a file you need very few things to write up a simplest C# code. First you need to verify the state of the FileUpload control whether it contains a file or not otherwise the properties accessed using FileUpload control object may throw as error or exception of "System.NullReferenceException: Object reference not set to an instance of an object.". You can use the HasFile property to verify that the fileupload control contains a file that is to be uploaded.

Next you need a method to specify the location where to save the uploaded file. The ASP.Net FileUpload control caches the file contents into the server memory before executing the server code. That is why you just need to call the SaveAs method of PostedFile object reference type property of fileupload control specified with location where you want to save the uploaded file.

Sample Code for ASP.Net File Uploading using C#

HTML Code:










In the HTML code we have used ASP.Net button control to provide the server side code mechanism that will allow the user to upload the file by clicking the button. You can specify your code in the associated click event handler of button control to upload the file to the server.

C# Code:

protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
// SaveAs method of PostedFile property used
// to save the file at specified rooted path
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/App_Data") + System.IO.Path.DirectorySeparatorChar + FileUpload1.PostedFile.FileName);

// success message
Label1.Text = "File " + FileUpload1.PostedFile.FileName + " uploaded successfully.";
}
catch (Exception ex)
{
// error message
Label1.Text = "Some problem occurred while uploading the file. Please try after some time.";
}
}
else
{
// warning message
Label1.Text = "Please choose a file to upload.";
}
}

By default SaveAs method of PostedFile property accepts the full rooted path to save the file at a specified location. You can use the Server.MapPath function to generate the full rooted path mapped according to the current web application as we have done in the above C# code. You can enable or disable the rooted path configuration of SaveAs method by specifying it in the httpRuntime setting of web.config file using requireRootedSaveAsPath attribute. It accepts the Boolean type value to enable/disable the feature. If you will specify its value as “false” then SaveAs method automatically maps the path to the "C:\Windows\System32" directory of the web server to save the uploaded file. So, it is recommended to use the default value for the requireRootedSaveAsPath configuration setting of SaveAs method.

You can specify the value for requireRootedSaveAsPath property inside httpRuntime element of system.web section of web.config file as follows:

----------

protected void UploadButton_Click(object sender, EventArgs e) {     if(FileUploadControl.HasFile)     {         try         {             if(FileUploadControl.PostedFile.ContentType == "image/jpeg")             {                 if(FileUploadControl.PostedFile.ContentLength < 102400)                 {                     string filename = Path.GetFileName(FileUploadControl.FileName);                     FileUploadControl.SaveAs(Server.MapPath("~/") + filename);                     StatusLabel.Text = "Upload status: File uploaded!";                 }                 else                     StatusLabel.Text = "Upload status: The file has to be less than 100 kb!";             }             else                 StatusLabel.Text = "Upload status: Only JPEG files are accepted!";         }         catch(Exception ex)         {             StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;         }     } }




protected void UploadButton_Click(object sender, EventArgs e)
{
if(FileUploadControl.HasFile)
{
try
{
if(FileUploadControl.PostedFile.ContentType == "image/jpeg")
{
if(FileUploadControl.PostedFile.ContentLength < 102400)
{
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
StatusLabel.Text = "Upload status: File uploaded!";
}
else
StatusLabel.Text = "Upload status: The file has to be less than 100 kb!";
}
else
StatusLabel.Text = "Upload status: Only JPEG files are accepted!";
}
catch(Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}