Microsoft KB Archive/816150

= How to upload a file to a Web site by using Visual C# =

Article ID: 816150

Article Last Modified on 6/1/2007

-

APPLIES TO


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

-



SUMMARY
''This article descibes how to upload a file by using Microsoft Visual C#. The uploaded file is validated if it exists on the server. This article uses the EncType attribute of the form to achieve the functionality.''



INTRODUCTION
This step-by-step article discusses how to upload an existing image file from your local hard disk drive to a Web site. An Input control is used to upload an image from your local computer. This file that is being uploaded is validated against the server to make sure that you do not overwrite an existing file that is already been uploaded.

Requirements
This article assumes that you are familiar with the following topics:
 * Web Applications
 * Microsoft ASP.NET

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
 * Microsoft Visual C# .NET or Microsoft Visual C# 2005
 * Microsoft Internet Information Services (IIS) version 5.0 or later

Create an ASP.NET Web Form
 Start Microsoft Visual Studio .NET 2003 or Microsoft Visual Studio 2005. On the File menu, point to New, and then click Project.

Note In Visual Studio 2005, point to New on the File menu, and then click Web Site. Under Project Types, click Visual C# Projects. Under Templates, click ASP.NET Web Application.

Note In Visual Studio 2005, select Visual C# on the right of Language. Under Templates, click ASP.NET Web Site. In the Location box, type the following location, and then click OK:

http:// /

Note is a placeholder for the name of your Web server. is a placeholder for the name of your application.

By default, WebForm1.aspx is created.

Note In Visual Studio 2005, select HTTP on the right of Location, and then type http://WebServerName . On the View menu, click HTML source.

Note In Visual Studio 2005, click Code on the View menu.

Modify the form attributes
In the HTML window of WebForm1, replace the form tag with the following:  The EncType attribute specifies the format of the data that is posted. The browser uses this attribute to encode the information that is posted to the server. The action attribute in this code specifies that the page will process the request. By default, the method attribute of the form is set to post so that you can send large amounts of data in the transaction.

Add the Input control to specify the file that you want to upload to the server
  In the HTML window of WebForm1, add the following code between the opening and the closing tags: <INPUT id=&quot;oFile&quot; type=&quot;file&quot; runat=&quot;server&quot; NAME=&quot;oFile&quot;> This Input control specifies the file that you want to upload to the server. </li>  You can add a text string in front of the control to prompt the user. Type the following text in front of the Input control in the HTML window of WebForm1: Select the image file to upload to the server: </li></ol>

back to the top

Add a Button control
  In the HTML window of WebForm1, add the following code between the opening and closing tags, after the Input control code: <asp:button id=&quot;btnUpload&quot; type=&quot;submit&quot; text=&quot;Upload&quot; runat=&quot;server&quot;></asp:button> </li> This Button control is used to upload the file that you specified in the Input control.</li></ol>

Create a Panel control that contains a single label to display the output
In the HTML window of WebForm1, add the following code between the opening and closing tags, after the Button control code: <asp:Panel ID=&quot;frmConfirmation&quot; Visible=&quot;False&quot; Runat=&quot;server&quot;> <asp:Label id=&quot;lblUploadResult&quot; Runat=&quot;server&quot;></asp:Label> </asp:Panel> This code is used to display the message to indicate whether the file upload is successful. To display this output, a Panel control is created that contains a single label.

Upload the file on the Button Click event
The code in this section retrieves the file from the local file system, checks to see if the file already exists on the server, and then uploads the file to the Web site. To add this code, follow these steps:  Double-click the Upload button that was created in the &quot;Add a Button control&quot; section of this article to create an event handler for the Click event of the button control.</li>  Add the following code at the top of the Code window: using System.IO; </li>  Add the following code to the Click event handler for the Upload button: string strFileName; string strFilePath; string strFolder; strFolder = Server.MapPath(&quot;./&quot;) ; // Retrieve the name of the file that is posted. strFileName = oFile.PostedFile.FileName; strFileName = Path.GetFileName(strFileName); if(oFile.Value != &quot;&quot;) {                      // Create the folder if it does not exist. if(!Directory.Exists(strFolder)) {                   Directory.CreateDirectory(strFolder); }               // Save the uploaded file to the server. strFilePath = strFolder + strFileName;

if(File.Exists(strFilePath)) {                   lblUploadResult.Text = strFileName + &quot; already exists on the server!&quot;; }               else {                   oFile.PostedFile.SaveAs(strFilePath); lblUploadResult.Text = strFileName + &quot; has been successfully uploaded.&quot;; }

}              else {                       lblUploadResult.Text = &quot;Click 'Browse' to select the file to upload.&quot;; }       // Display the result of the upload. frmConfirmation.Visible = true; </li> On the File menu, click Save All.</li></ol>

Verify that the upload action works
 On the Debug menu, click Start to build and to run the application. A text box and a command button appear.</li> Type the path of the image file in the text box, or click Browse to locate the image file on your local computer.</li> Click Upload to send the file to the server. If the file is unique, you receive a message that the upload succeeded. If the file already exists on the server, you receive an appropriate message. The files that you upload from this application are saved in the location : C:\inetpub\wwwroot\ on the local hard disk.</li> To make this application work in the Microsoft .NET Framework 1.0, allow Full Control access to the ASPNET user. To do this, follow these steps:  <li>Locate the application folder in Windows Explorer. The path is C:\inetpub\wwwroot\ .</li> <li>Right-click the  folder, and then click Properties. The  Properties dialog box appears.</li> <li>Click the Security tab.</li> <li>Click Add. The Select Users or Groups dialog box appears.

Note In Visual Studio 2005, the Select Users, Computers, or Groups dialog box appears.</li> <li>Type ASPNET in the Enter the object names to select box, and then click OK.</li> <li>In the  Properties dialog box, click the ASPNET user in the Group or user names list.</li> <li>Under Allow, click to select the Full Control check box, and then click OK.</li></ol> </li></ol>

Complete code listing
WebForm1.aspx <%@ Page language=&quot;c#&quot; Codebehind=&quot;WebForm1.aspx.cs&quot; AutoEventWireup=&quot;false&quot; Inherits=&quot;Howto.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 .NET 7.1&quot;> <meta name=&quot;CODE_LANGUAGE&quot; Content=&quot;C#&quot;> <meta name=&quot;vs_defaultClientScript&quot; content=&quot;JavaScript&quot;> <meta name=&quot;vs_targetSchema&quot; 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; runat=&quot;server&quot; EncType=&quot;multipart/form-data&quot; action=&quot;WebForm1.aspx&quot;> Image file to upload to the server: <INPUT id=&quot;oFile&quot; type=&quot;file&quot; runat=&quot;server&quot; NAME=&quot;oFile&quot;> <asp:button id=&quot;btnUpload&quot; type=&quot;submit&quot; text=&quot;Upload&quot; runat=&quot;server&quot;></asp:button> <asp:Panel ID=&quot;frmConfirmation&quot; Visible=&quot;False&quot; Runat=&quot;server&quot;> <asp:Label id=&quot;lblUploadResult&quot; Runat=&quot;server&quot;></asp:Label> </asp:Panel>

</HTML> 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; using System.IO; namespace ApplicationName {   ///     /// Summary description for WebForm1. ///    public class WebForm1 : System.Web.UI.Page {       protected System.Web.UI.WebControls.Button btnUpload; protected System.Web.UI.WebControls.Label lblUploadResult; protected System.Web.UI.WebControls.Panel frmConfirmation; protected System.Web.UI.HtmlControls.HtmlInputFile oFile; 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.btnUpload.Click += new System.EventHandler(this.btnUpload_Click); this.Load += new System.EventHandler(this.Page_Load);

}       #endregion

private void btnUpload_Click(object sender, System.EventArgs e)       { string strFileName; string strFilePath; string strFolder; strFolder = Server.MapPath(&quot;./&quot;) ; // Get the name of the file that is posted.

strFileName = oFile.PostedFile.FileName; strFileName = Path.GetFileName(strFileName); if(oFile.Value != &quot;&quot;) {                      // Create the directory if it does not exist. if(!Directory.Exists(strFolder)) {                   Directory.CreateDirectory(strFolder); }               // Save the uploaded file to the server. strFilePath = strFolder + strFileName;

if(File.Exists(strFilePath)) {                   lblUploadResult.Text = strFileName + &quot; already exists on the server!&quot;; }               else {                   oFile.PostedFile.SaveAs(strFilePath); lblUploadResult.Text = strFileName + &quot; has been successfully uploaded.&quot;; }

}              else {                       lblUploadResult.Text = &quot;Click 'Browse' to select the file to upload.&quot;; }       // Display the result of the upload. frmConfirmation.Visible = true;

}   } } Note The code generated in Visual Studio 2005 is different from the code generated in Visual Studio .NET.

Troubleshooting

 * 1) Open the Machine.config file that is located on your computer in the CONFIG folder under the path where you installed the runtime.
 * 2) Find the <processModel> section in the Machine.config file, change the user and the password attributes to the name and the password of the user who you want W3wp.exe or Aspnet_wp.exe to run under, and then save the Machine.config file.
 * 3) Locate the Temporary ASP.NET Files folder that is located in the CONFIG folder. Right-click the Temporary ASP.NET Files folder, and then click Properties.
 * 4) In the Temporary ASP.NET Files Properties dialog box, click the Security tab.
 * 5) Click Advanced.
 * 6) In the Access Control Settings for Temporary ASP.NET Files dialog box, click Add.
 * 7) In the dialog box, type the user name in the Name box, and then click OK.
 * 8) In the Permission Entry for Temporary ASP.NET Files dialog box, give the user full permissions, and then click OK to close the Temporary ASP.NET Files Properties dialog box.

<div class="references_section">