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.
Windows XP Professional SP2, Windows Server 2003, Visual Studio 2005
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
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
<pre style="background-color: #ffffff; margin: 0em; width: 100%; font-family: consolas,'Courier New',courier,monospace; font-size: 12px">if (FileUpload1.HasFile)
lblStatus.Text = "Uploading File " + FileUpload1.FileName;
lblStatus.Text = "File Successfully Uploaded";
lblStatus.Text = "Unable to save the file";
lblStatus.Text = "You have to select a file to upload";
Visual Basic .NET
<pre style="background-color: #ffffff; margin: 0em; width: 100%; font-family: consolas,'Courier New',courier,monospace; font-size: 12px">If FileUpload1.HasFile Then
lblStatus.Text = "Uploading File " + FileUpload1.FileName
FileUpload1.SaveAs("C:\\Files\\" + FileUpload1.FileName)
lblStatus.Text = "File Successfully Uploaded"
lblStatus.Text = "Unable to save the file"
lblStatus.Text = "You have to select a file to upload"
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.
(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.
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.