File uploader in C#


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.

Up Next
    Ebook Download
    View all
    Learn
    View all