Microsoft KB Archive/323246

= How to upload a file to a Web server in ASP.NET by using Visual C# .NET =

Article ID: 323246

Article Last Modified on 5/21/2007

-

APPLIES TO


 * Microsoft ASP.NET 1.0
 * Microsoft Visual C# .NET 2002 Standard Edition
 * Microsoft ASP.NET 1.1
 * Microsoft Visual C# .NET 2003 Standard Edition

-



This article was previously published under Q323246



For a Microsoft Visual Basic .NET version of this article, see 323245.

IN THIS TASK
SUMMARY Create the ASP.NET Application Create the Data Directory Modify the WebForm1.aspx Page Add the Upload Code to the WebForm1.aspx.cs Code-Behind File Test the Application Upload Larger Files Complete Code Listing
 * WebForm1.aspx
 * WebForm1.aspx.cs

REFERENCES



SUMMARY
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.

back to the top

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.

back to the top

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.  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. To change the folder name to Data, right-click NewFolder1, click Rename, and then type Data . 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

 To change the security settings to grant write permissions to the Data directory, right-click Data, and then click Properties. In the Data Properties dialog box, click the Security tab, and then click Add. 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. Click the aspnet_wp account ( \ASPNET) account, and then click to select the Allow check boxes for the following permissions:

<ul> Read and Execute</li> List Folder Contents</li> Read</li> Write</li></ul>

Click to clear any other Allow and Deny check boxes.</li> Click OK to close the Data Properties dialog box. You have successfully modified the Data directory permissions to accept user uploaded files.</li></ol>

back to the top

Modify the WebForm1.aspx page
To modify the HTML code of the WebForm1.aspx file to permit users to upload files, follow these steps: <ol> Return to the open instance of Visual Studio .NET. WebForm1.aspx should be open in the Designer window.</li> To view the HTML source of the WebForm1.aspx page, right-click WebForm1.aspx in the Designer window, and then click View HTML Source.</li>  Locate the following HTML code, which contains the tag: <form id=&quot;Form1&quot; method=&quot;post&quot; runat=&quot;server&quot;> </li>  Add the enctype=&quot;multipart/form-data&quot; name-value attribute to the tag as follows: <form id=&quot;Form1&quot; method=&quot;post&quot; enctype=&quot;multipart/form-data&quot; runat=&quot;server&quot;> </li>  After the opening tag, add the following code: <INPUT type=file id=File1 name=File1 runat=&quot;server&quot; /> <input type=&quot;submit&quot; id=&quot;Submit1&quot; value=&quot;Upload&quot; runat=&quot;server&quot; /> </li>  Verify that the HTML tag appears as follows: <form id=&quot;Form1&quot; method=&quot;post&quot; enctype=&quot;multipart/form-data&quot; runat=&quot;server&quot;> <INPUT type=file id=File1 name=File1 runat=&quot;server&quot; /> <input type=&quot;submit&quot; id=&quot;Submit1&quot; value=&quot;Upload&quot; runat=&quot;server&quot; /> </li></ol>

back to the top

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: <ol> On the View menu, click Design.</li>  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) {

} </li>  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 {                   </li>  Locate the following code: private void Submit1_ServerClick(object sender, System.EventArgs e) { </li> <li> 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(&quot;Data&quot;) + &quot;\\&quot; + fn; try {       File1.PostedFile.SaveAs(SaveLocation); Response.Write(&quot;The file has been uploaded.&quot;); }   catch ( Exception ex ) {       Response.Write(&quot;Error: &quot; + 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(&quot;Please select a file to upload.&quot;); } This code first verifies that a file has been uploaded. If no file was selected, you receive the &quot;Please select a file to upload&quot; 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. </li> <li> 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(&quot;Data&quot;) + &quot;\\&quot; + fn; try {           File1.PostedFile.SaveAs(SaveLocation); Response.Write(&quot;The file has been uploaded.&quot;); }       catch ( Exception ex ) {           Response.Write(&quot;Error: &quot; + 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(&quot;Please select a file to upload.&quot;); } } </li></ol>

back to the top

Test the application
To build your Visual Studio .NET solution and to test the application, follow these steps:
 * 1) On the Build menu, click Build Solution.
 * 2) In Solution Explorer, right-click WebForm1.aspx, and then click View in Browser.
 * 3) After WebForm1.aspx opens in the browser, click Browse.
 * 4) In the Choose File dialog box, select a file that is smaller than 4 megabytes (MB), and then click Open.
 * 5) To upload the file, click Upload. Notice that the file uploads to the Web server and that you receive the &quot;The file has been uploaded&quot; message.
 * 6) Return to the open instance of Windows Explorer, and then locate the Data directory.
 * 7) Verify that the file has been uploaded to the Data directory.

back to the top

Upload larger files
By default, ASP.NET only permits files that are 4,096 kilobytes (KB) (or 4 MB) or less to be uploaded to the Web server. To upload larger files, you must change the maxRequestLength parameter of the <httpRuntime> section in the Web.config file.

Note When the maxRequestLength attribute is set in the Machine.config file and then a request is posted (for example, a file upload) that exceeds the value of maxRequestLength, a custom error page cannot be displayed. Instead, Microsoft Internet Explorer will display a &quot;Cannot find server or DNS&quot; error message.

If you want to change this setting for all of the computer and not just this ASP.NET application, you must modify the Machine.config file.

By default, the <httpRuntime> element is set to the following parameters in the Machine.config file: <httpRuntime executionTimeout=&quot;90&quot; maxRequestLength=&quot;4096&quot; useFullyQualifiedRedirectUrl=&quot;false&quot; minFreeThreads=&quot;8&quot; minLocalRequestFreeThreads=&quot;4&quot; appRequestQueueLimit=&quot;100&quot; /> The Machine.config file is located in the \ \Microsoft.NET\Framework\ \CONFIG directory.

back to the top

WebForm1.aspx
<%@ Page language=&quot;c#&quot; Codebehind=&quot;WebForm1.aspx.cs&quot; AutoEventWireup=&quot;false&quot; Inherits=&quot;CSharpUpload.WebForm1&quot; %> <!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0 Transitional//EN&quot; > <HTML> <HEAD> WebForm1 <meta name=&quot;GENERATOR&quot; Content=&quot;Microsoft Visual Studio 7.0&quot;> <meta name=&quot;CODE_LANGUAGE&quot; Content=&quot;C#&quot;> <meta name=vs_defaultClientScript content=&quot;JavaScript&quot;> <meta name=vs_targetSchema content=&quot;http://schemas.microsoft.com/intellisense/ie5&quot;> </HEAD> <body MS_POSITIONING=&quot;GridLayout&quot;> <form id=&quot;Form1&quot; method=&quot;post&quot; enctype=&quot;multipart/form-data&quot; runat=&quot;server&quot;> <INPUT type=file id=File1 name=File1 runat=&quot;server&quot; > <input type=&quot;submit&quot; id=&quot;Submit1&quot; value=&quot;Upload&quot; runat=&quot;server&quot; NAME=&quot;Submit1&quot;>

</HTML> back to the top

WebForm1.aspx.cs
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls;

namespace CSharpUpload {   ///     /// Summary description for WebForm1. ///    public class WebForm1 : System.Web.UI.Page {       protected System.Web.UI.HtmlControls.HtmlInputFile File1; protected System.Web.UI.HtmlControls.HtmlInputButton Submit1; private void Page_Load(object sender, System.EventArgs e)       { // Put user code to initialize the page here }

#region Web Form Designer generated code override protected void OnInit(EventArgs e)       { //            // CODEGEN: This call is required by the ASP.NET Web Form Designer. //            InitializeComponent; base.OnInit(e); }       ///         /// Required method for Designer support - do not modify /// the contents of this method with the code editor. ///        private void InitializeComponent {               this.Submit1.ServerClick += new System.EventHandler(this.Submit1_ServerClick); this.Load += new System.EventHandler(this.Page_Load);

}       #endregion

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(&quot;Data&quot;) + &quot;\\&quot; + fn; try {                   File1.PostedFile.SaveAs(SaveLocation); Response.Write(&quot;The file has been uploaded.&quot;); }               catch ( Exception ex ) {                   Response.Write(&quot;Error: &quot; + 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 return a generic error message. }           }            else {               Response.Write(&quot;Please select a file to upload.&quot;); }       }    } } back to the top

<div class="moreinformation_section">

MORE INFORMATION
Theoretically, the maximum file upload size is fairly large. However, because of ASP.NET health monitoring, you cannot upload very large files in ASP.NET. The ASP.NET worker process has a virtual address space of 2 gigabytes (GB). However, the ASP.NET worker process only uses a little more than 1 GB because of health monitoring and memory fragmentation.

During the upload process, ASP.NET loads the whole file in memory before the user can save the file to the disk. Therefore, the process may recycle because of the memoryLimit attribute of the processModel tag in the Machine.config file. The memoryLimit attribute specifies the percentage of physical memory that the ASP.NET worker process can exhaust before the process is automatically recycled. Recycling prevents memory leaks from causing ASP.NET to crash or to stop responding.

Additionally, other factors play a role in the maximum file size that can be uploaded. These factors include available memory, available hard disk space, processor speed, and current network traffic. With regular traffic of files being uploaded, Microsoft recommends that you use a maximum file size in the range of 10 to 20 megabytes (MB). If you rarely upload files, the maximum file size may be 100 MB.

Note You can upload files that are larger than 100 MB in ASP.NET. However, Microsoft recommends that you follow the maximum file upload sizes that are mentioned in this article. To determine more precise file sizes, perform stress testing on computers that are similar to the ones that will be used in production.

You may notice the following error messages if you encounter file size limits during the file upload process: <ul> <li>

The page cannot be displayed.

</li> <li>

Server Application is Unavailable

In the event log, the error message will be similar to the following: aspnet_wp.exe (PID: ) was recycled because memory consumption exceeded the  MB (  percent of available RAM). </li> <li>

Exception of type System.OutOfMemoryException was thrown.

</li></ul>

You may also find that uploads occur very slowly. If you watch the Aspnet_wp.exe process in Windows Task Manager, you will notice that the memory delta changes by 64 KB every 1 to 2 seconds. Depending on the size of the file, this delay may cause the ASP.NET worker process to recycle because of a responseDeadlock error.

<div class="references_section">