Learn how to work with FileUpload Control

Uploading files to a folder on the web server is made easy with ASP.NET 2.0. In this step-by-step article, you will learn how to achieve this task with the help of code samples in C# and Visual Basic .NET.

Requirements

Windows XP Professional SP2, Windows Server 2003, Visual Studio 2005

Steps

1. Start Visual Studio 2005

2. Drag and Drop a FileUpload control from the Toolbox onto the design area. I didn’t modify its ID property but you can do so if you wish.

3. Drag and Drop a Button control and supply the following properties
ID: btnUpload
Text: Upload

4. Drag and Drop a Label control and modify its ID property (Example: lblStatus)
You have to delete the default Text by erasing the value of Text property. You should also modify its ForeColor as the default color is White.
Note: You can also double click a control from the Toolbox.

5. Double click the Button control and paste the following code

Visual C# .NET

if (FileUpload1.HasFile)
{
try
{
lblStatus.Text = "Uploading File " + FileUpload1.FileName;
FileUpload1.SaveAs("C:\\Files\\" +FileUpload1.FileName);
lblStatus.Text = "File Successfully Uploaded";
}
catch
{
lblStatus.Text = "Unable to save the file";
}
}
else
{
lblStatus.Text = "You have to select a file to upload";
}
}

Visual Basic .NET

If FileUpload1.HasFile Then
Try
lblStatus.Text = "Uploading File " + FileUpload1.FileName
FileUpload1.SaveAs("C:\\Files\\" + FileUpload1.FileName)
lblStatus.Text = "File Successfully Uploaded"
Catch
lblStatus.Text = "Unable to save the file"
End Try
Else
lblStatus.Text = "You have to select a file to upload"
End If

Make sure that you have created a folder named Files on the C drive before attempting to run this program. Otherwise, the catch block will be executed. If there are no files to upload then the application will execute the else block.

6. Run the application, browse for a file from your local hard drive and click on the Upload button. If everything works out fine then you should be able to view the uploaded file inside the Files directory.

Notes

(1) Visual Studio 2005 is not compulsory for working with the above example. Just download the code files from the links given below and copy them to Inetpub/wwwroot folder and execute. You need to install .NET Framework 2.0 before running the code.

(2) Sometimes, you will have to give write permission for the folder to which you are attempting to upload the files. This process requires access to the remote server. If you don’t have the access to the web server then contact your hosting service provider.

(3) You will have to employ a suitable method of authentication before allowing users to upload files. This will prevent unauthorized uploads which can ultimately harm your server.

Summary

In this article, you have learned how to upload files with the help of FileUpload control using ASP.NET 2.0 with the help of an example.

One Response

Leave a Comment