SIGN UP MEMBER LOGIN:    
ARTICLE

File uploader in C#

Posted by Munir Shaikh Articles | ASP.NET Controls in C# February 13, 2006
This article shows a simple Web user control for uploading any file up to 2 MB to the specified folder using C#.
Reader Level:
Download Files:
 

This is very basic level small user control, in which we can discuss how to create web user control.

To create user controls follow the steps:

  1. Right click on project
  2. Click on Add
  3. Select New Item
  4. Select Web User Control
  5. Specify some Name

I have given name to this file as "uploader.ascx" and kept this file under "userControl" for simplicity purpose.

On this page I am having following controls:

  1. <INPUT id="fileUpload" type="file" Runat="server" NAME="fileUpload">

  2. <asp:label id="lblMessage" runat="server" Width="416px" Font-Size="10" Font-Name="verdana"></asp:label> 

  3. <asp:button id="btnSave" runat="server" Text="Upload.."></asp:button>

At the code behind of above file I am having following function

public string uploadFile(string fileName,string folderName)

{

          if(fileName=="")

          {

                    return "Invalid filename supplied";

          }

          if(fileUpload.PostedFile.ContentLength==0)

          {

                    return "Invalid file content";

          }

                    fileName = System.IO.Path.GetFileName(fileName);

          if(folderName=="")

                    {

                    return "Path not found";

                    }  

                    try

                    {

                    if (fileUpload.PostedFile.ContentLength<=2048000)

                              {    

          fileUpload.PostedFile.SaveAs(Server.MapPath(folderName)+"\\"+fileName);    

                                       return "File uploaded successfully";    

                             }

                             else

                    {

                              return "Unable to upload,file exceeds maximum limit";

                             }

          }

                    catch(UnauthorizedAccessException ex)

                    {

                    return ex.Message + "Permission to upload file denied";

                    }  

}

The above function takes care of following things before uploading file to the folder

  1. Invalid file name supplied.
  2. If file not exists or content length 0.
  3. Folder name exists.

Error Handling

While uploading done with UnauthorizedAccessException and returned with the message

On upload button click I am having following code

private void btnSave_Click(object sender, System.EventArgs e)

{

          string strFilename, strMessage;

          strFilename = fileUpload.PostedFile.FileName.ToString();

          strMessage = uploadFile(strFilename,ConfigurationSettings.AppSettings["folderPath"]);

          lblMessage.Text = strMessage;

          lblMessage.ForeColor = Color.Red;

}

I have made use of Web.config file, in which I have added attribute as follows under:

<configuration>
      
<appSettings>
        
<add key="folderPath" value="Images"></add>
     
</appSettings>

i.e. I have set up path of folder to upload image

To access control in project, I have added page called as "uploadTester.aspx" to the project in which I have added following line:

<%@ Register TagPrefix="img" TagName="Uploader" src="userControl/uploader.ascx"%>

Which says that this control is register to this page with specified source.

And in HTML code I have added following code inside form tag:

<img:Uploader runat="server" id="Uploader1"></img:Uploader>

That's all about

General:

To upload any of the file in respective folder user need to have permission for writing to the folder so please follow the following steps to prevent from the error.

Set permission to virtual directory by following steps in IIS

  • Right Click on virtual directory which you have created for this project. Under directory Tab you will find
        1)Read
        2)Log Visits
        3)Index this resources
           Are marked as checked (enables) in addition to this make
        4)Write access enabled or checked
  • Click on apply
  • Click on ok

This will set right permission to entire virtual directory, this way we can minimize error from the front end for permission / access denied.

Other way to solve permission denied issue is to go to actual folder "images" by using physical path and follow these steps:

  • Right click folder
  • Sharing Tab
  • Enable share this folder radio button
  • Click Apply
  • Click Ok

If u are using this code on 2000 server you should do following:

  • Right click respective folder
  • Go to security tab
  • Select Everyone user
  • Apply full control
  • click on ok

Kindly go through zip file for entire code.

Login to add your contents and source code to this article
Article Extensions
Contents added by sunil tarar on Nov 06, 2009
share this article :
post comment
 

Adding user id to the upload so that i can retrieve them using the userid

Posted by just mat Aug 12, 2011

Hi............Munir sir....
Nice code......

Posted by yogesh kolpe Jun 04, 2009

Pls Help me. I have created in voice xml Recorded data. I want to Recorded data upload to IIS server folder with out upload control using c# aspx version 2.0.

Posted by siva prasad Feb 07, 2008

Hello Sir I m Asking that can This artical work with asp.net 2.0 can u send me details on call.narendra@gmail.com As soon as possible Narendra

Posted by Narendra Kumar Gautam Nov 23, 2007

As u said i go through the error console in Mozilla and found the following error:'up_div has no properties'.How can i Solve this issue?

Posted by jobin thomas Aug 29, 2007
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Team Foundation Server Hosting
Become a Sponsor