How to upload a file to a Web server in ASP.NET

This step-by-step article describes how to upload a file to a Web server by using Visual C# .NET. In this article, you create a Microsoft ASP.NET file (WebForm1.aspx) and its related code-behind file (WebForm1.aspx.cs) to upload files to a directory that is named Data.

Create an ASP.NET application

In Microsoft Visual Studio .NET, follow these steps to create a new application to upload files to the Web server:

  1. Start Microsoft Visual Studio .NET.
  2. On the File menu, point to New, and then click Project.
  3. In the New Project dialog box, click Visual C# Projects under Project Types, and then click ASP.NET Web Application under Templates.
  4. In the Location box, type the URL to create the project. For this example, type http://localhost/CSharpUpload, which creates the default project name of CSharpUpload. Notice that the WebForm1.aspx file loads in the Designer view of Visual Studio .NET.

 

Create the data directory

After you create the application, you create the Data directory that will accept uploaded files. After you create this directory, you must also set write permissions for the ASPNET worker account.

  1. In the Solution Explorer window of Visual Studio .NET, right-click CSharpUpload, point to Add, and then click New Folder. By default, a new folder that is named NewFolder1 is created.
  2. To change the folder name to Data, right-click NewFolder1, click Rename, and then type Data.
  3. Start Windows Explorer, and then locate the Data file system folder that you created in step 2. By default, this folder is located in the following folder:
    C:\Inetpub\wwwroot\CSharpUpload\Data
  4. To change the security settings to grant write permissions to the Data directory, right-click Data, and then click Properties.
  5. In the Data Properties dialog box, click the Security tab, and then click Add.
  6. In the Select Users or Groups dialog box, click the ASPNET account, and then click Add. Click OK to close the Select Users or Groups dialog box.
  7. Click the aspnet_wp account (computername\ASPNET) account, and then click to select the Allow check boxes for the following permissions:
    • Read and Execute
    • List Folder Contents
    • Read
    • Write

    Click to clear any other Allow and Deny check boxes.

  8. Click OK to close the Data Properties dialog box. You have successfully modified the Data directory permissions to accept user uploaded files.

 

Modify the WebForm1.aspx page

To modify the HTML code of the WebForm1.aspx file to permit users to upload files, follow these steps:

  1. Return to the open instance of Visual Studio .NET. WebForm1.aspx should be open in the Designer window.
  2. To view the HTML source of the WebForm1.aspx page, right-click WebForm1.aspx in the Designer window, and then click View HTML Source.
  3. Locate the following HTML code, which contains the <form> tag:

    <form id="Form1" method="post" runat="server">

  4. Add the enctype=”multipart/form-data” name-value attribute to the <form> tag as follows:

    <form id="Form1" method="post" enctype="multipart/form-data" runat="server">

  5. After the opening <form> tag, add the following code:

    <INPUT type=file id=File1 name=File1 runat="server" />
    <br>
    <input type="submit" id="Submit1" value="Upload" runat="server" />

  6. Verify that the HTML <form> tag appears as follows:

    <form id="Form1" method="post" enctype="multipart/form-data" runat="server">
    <INPUT type=file id=File1 name=File1 runat="server" />
    <br>
    <input type="submit" id="Submit1" value="Upload" runat="server" />
    </form>

 

Add the upload code to the WebForm1.aspx.cs code-behind file

To modify the WebForm1.aspx.cs code-behind file so that it accepts the uploaded data, follow these steps:

  1. On the View menu, click Design.
  2. Double-click Upload. Visual Studio opens the WebForm1.aspx.cs code-behind file and automatically generates the following method code:

    private void Submit1_ServerClick(object sender, System.EventArgs e)
    {
    
    }

  3. Verify that the following code exists at the class level of the WebForm1.cs file:

    protected System.Web.UI.HtmlControls.HtmlInputFile File1;
    protected System.Web.UI.HtmlControls.HtmlInputButton Submit1;

    If this code does not exist in the file, add the code into the file after the following line:

    public class WebForm1 : System.Web.UI.Page
    {

  4. Locate the following code:

    private void Submit1_ServerClick(object sender, System.EventArgs e)
    {

  5. Press ENTER to add a blank line, and then add the following code:

    if( ( File1.PostedFile != null ) && ( File1.PostedFile.ContentLength > 0 ) )
    {
    	string fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);
    	string SaveLocation = Server.MapPath("Data") + "\\" +  fn;
    	try
    	{
    		File1.PostedFile.SaveAs(SaveLocation);
    		Response.Write("The file has been uploaded.");
    	}
    	catch ( Exception ex )
    	{
    		Response.Write("Error: " + ex.Message);
    		//Note: Exception.Message returns a detailed message that describes the current exception. 
    		//For security reasons, we do not recommend that you return Exception.Message to end users in 
    		//production environments. It would be better to put a generic error message. 
    	}
    }
    else
    {
    	Response.Write("Please select a file to upload.");
    }

    This code first verifies that a file has been uploaded. If no file was selected, you receive the “Please select a file to upload” message. If a valid file is uploaded, its file name is extracted by using the System.IO namespace, and its destination is assembled in a SaveAs path. After the final destination is known, the file is saved by using the File1.PostedFile.SaveAs method. Any exception is trapped, and the exception message is displayed on the screen.

  6. Verify that the Submit1 subroutine appears as follows:

    private void Submit1_ServerClick(object sender, System.EventArgs e)
    {
    	if( ( File1.PostedFile != null ) && ( File1.PostedFile.ContentLength > 0 ) )
    	{
    		string fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);
    		string SaveLocation = Server.MapPath("Data") + "\\" +  fn;
    		try
    		{
    			File1.PostedFile.SaveAs(SaveLocation);
    			Response.Write("The file has been uploaded.");
    		}
    		catch ( Exception ex )
    		{
    			Response.Write("Error: " + ex.Message);
    			//Note: Exception.Message returns detailed message that describes the current exception. 
    			//For security reasons, we do not recommend you return Exception.Message to end users in 
    			//production environments. It would be better just to put a generic error message. 
    		}
    	}
    	else
    	{
    		Response.Write("Please select a file to upload.");
    	}
    }

Advertisements

About Saad Khan

Saad is an ASP.NET developer with 4 years of experience, and has also made a number of contributions to the Sitefinity marketplace and community. He loves to explore new code, and create innovative tools and procedures while exploring new approaches in his work with Sitefinity and MVC. As an experienced .NET developer, he frequents both Telerik and Microsoft technologies. In his spare time, Saad is an avid gamer and movie fanatic, and also experiments with new and interesting tools on the Microsoft platform.​​

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: