Write For Us

Mainpulating Files and Directories in ASP.NET

Let suppose, you have to enable your website users to upload their pictures. Or suppose you have to place functionality of uploading product images along with the product description. In this article, we will explain how you can provide such functionalities.


We may need to manipulate files and directories on our web server in different ways. For example, applications need to create a new file, delete an existing file, modify the contents of an existing file, and check whether a file with given name exists or not. Similarly, directories are also required to be manipulated. ASP.Net gives us the opportunity to handle such operations using the namespace System.IO.

Important Classes for File and Directory Manipulation

Here are some of the important classes in the namespace System.IO:

  • Directory

  • DirectoryInfo

  • Drive

  • DriveInfo

  • File

  • FileInfo

  • StreamWriter

  • StreamReader

  • TextWriter

  • TextReader

Before proceeding further, it's important to note that you need to make sure that appropriate security permissions are set on folders where you are manipulating your files and directories.

When you are doing it on your local development machine, you can set these permissions in this way:

  • Right click the website folder.

  • Select "properties" option.

  • Choose "Security" tab.

  • Under "Groups or User Names" label, check whether "ASPNET" user is added or not.

    • If added, make it sure that it has full permissions.

    • If not added, then click "Add", enter "ASPNET" object name. Click OK and assign full permissions.

When your site is live and you are doing it on hosting server, you need to know how your hosting service handles security settings. This procedure varies in different hosters. Some hosters may have provided you with some tool, which you can use to configure security settings on your folders. For example, WebHostForASP.NET provides its own Control Panel to handle all custom settings. Others may do it with some third party tool like Helm or Plesk.

How to Write a File on Web Server

Include System.IO name space with line
using System.IO;

and then look at the function bellow:

private void WriteFile()
    string FilePath = "C:\\Inetpub\\wwwroot\\test.txt";
    StreamWriter writer = new StreamWriter(FilePath);
    writer.Write("Sample text in line 1");
    writer.Write("Sample text in line 2");
    writer.Write("Sample text in line 3");

Execution of this code results in creation of a text file named "test.txt" in the path specified which contains this text:

Sample Text in Line 1
Sample Text in Line 2
Sample Text in Line 3

You may need to test whether a file with same name on same path already exists or not. You can do so using Exists property of FileInfo class.

    private void WriteFile()
        string filePath = "C:\\Inetpub\\wwwroot\\test.txt";
        FileInfo objFileInfo = new FileInfo(filePath);
        if (objFileInfo.Exists)
        StreamWriter writer = new StreamWriter(filePath);
        writer.Write("Sample Text in Line 1");
        writer.Write("Sample Text in Line 2");
        writer.Write("Sample Text in Line 3");

You may need to add some more text in an already existing file. AppendText() method of FileInfo class is used to achieve it.

string filePath = "C:\\Inetpub\\wwwroot\\test.txt";
FileInfo objFileInfo = new FileInfo(filePath);
StreamWriter writer = objFileInfo.AppendText();
writer.Write("Sample Text To Append with  Previous   goes here...");

Now, text in the file "test.txt" takes this form:

Sample Text in Line 1
Sample Text in Line 2
Sample Text in Line 3
Sample Text To Append with Previous goes here...

Extension property can be used to find the extension of FileInfo object.

string extension = objFileInfo.Extension();

Manipulating Directories in ASP.NET

Here are few methods and properties which can be used to manipulate directories: CreateDirectory method takes the string parameter which tells the directory path to create.

CreateSubDirectory method is used by a DirectoryInfo object to create a directory within the directory represented by calling DirectoryInfo object. Parent property of DirectoryInfo object can be used to return another object of DirectoryInfo representing parent of calling object.

//To Create a New Directory
DirectoryInfo objDirectoryInfo = Directory.CreateDirectory("C:\\TestDir");
//To Create a Directory Within an Existing Directory
DirectoryInfo childDir = objDirectoryInfo.CreateSubdirectory("Dir");
//To Get Parent of a Directory
DirectoryInfo parentDir = childDir.Parent;
//To Get All Files of a Directory
FileInfo[] fiList = parentDir.GetFiles();
//To Get Files of a Directory Starting With Text "abc"
FileInfo[] fiFilteredList = parentDir.GetFiles("abc*");
//To Delete an Empty Directory
//To Delete a Non Empty Directory

A practical example of file and directory manipulation in ASP.NET

Let's consider a practical example where we need manipulation of files and directories. You may have a website where your users can register. Along with asking them for other necessary information, you may want them to have an opportunity to upload their profile image or images demonstrating their business activities.

There are two approaches which can be used to save an image or any other file. One approach involves asking the user to give path of image they want to save. It gets the file path, makes a FileInfo object of this path, converts it into binary coding and saves it in database. A field of varbinary datatype is used to hold such data. Later on, when this image is required to retrieve, same binary code is fetched and converted into an image file. This approach is usually adopted when it's required to upload few files or images, because it involves database operations.

The other approach has nothing to do with database operations. It involves IO operations instead. You can save the files uploaded by users on server space. This is usually adopted when it's required to upload too many files on server. For example, a social networking site having too many users needs to upload multiple images by each user. In this approach, one important issue is to have the path where you can save the image user uploaded. A FileInfo or DirectoryInfo object doesn't take URL of the path where you have to save image. URL can be used only, if you are going to "get" file path from server. To create a directory in which you are going to upload the file, you need to give path information in this way:

string dipath = System.Web.HttpContext.Current.Server.MapPath("") + "\\UserImages\\" + Session["LoggedUserId"].ToString();

To achieve this, you need to have a file upload control and a button on your aspx page.

User image upload

<asp:FileUpload ID="EditFileUpload" runat="server" Width="289px" />
<asp:Button ID="btnSaveImage" runat="server" Height="20px" CssClass="button1" OnClick="btnSaveImage_Click" Text="Save" />

When user chooses an image file by clicking "Browse", its path is displayed in EditFileUpload control. Then user clicks "Save", btnSaveImage_Click method is called, which was defined in the code behind file.

We are going to follow a procedure where we put images uploaded by a user in a folder which is named by that user's ID. This user folder will be uploaded in a folder "UserImages" which we already created in our space. In other words, images uploaded by a user whose ID is 241 will have this path:

http://www.yourdomain.com/UserImages /241/Image2.jpg

and so on.

protected void btnSaveImage_Click(object sender, EventArgs e)
    int memberId = Convert.ToInt32(Session["LoggedUserId"]);
    if (EditFileUpload.HasFile)
        Byte[] bytes = EditFileUpload.FileBytes;
        System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
        System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
        string ImageName = EditFileUpload.FileName;
        string dipath = System.Web.HttpContext.Current.Server.MapPath("") + "\\UserImages\\" + Session["LoggedUserId"].ToString();
        //You may use this line to test this code on localhost
        //string imagePath = "http://localhost/virtualDir/UserImages/" + Session["LoggedUserId"].ToString() + "/" + EditFileUpload.FileName;
        string imagePath = "http://www.yourdomain.com/UserImages/" + Session["LoggedUserId"].ToString() + "/" + EditFileUpload.FileName;
        DirectoryInfo di = new DirectoryInfo("" + dipath + "");
        if (!(di.Exists))
        string serverPath = dipath + "\\" + ImageName;
        //Insert image path in database so that it can be retrieved later
        InsertUserImageInDB(imagePath, memberId);

To retrieve this image back, in order to display it on a web page, you just need an Image Control

<asp:Image ID="Image1" runat="server" Height="171px" Width="195px" />

To set its ImageUrl property, you need to retrieve it from database. Suppose, you get your desired results in a dataset named dsImages and it has a column "ImagePath" which contains the path of image you want to display.

Image1.ImageUrl = dsImages.Tables[0].Rows[0]["ImagePath"].ToString();

Where "ImagePath" may contain a value like this:


If you want to avoid writing such code in code behind, you can use another way to assign retrieved ImagePath value to ImageUrl Property of the image control. Here is the sample code:

<asp:Image ID="Image1" runat="server" ImageUrl='<%# Bind("ImagePath") %>' Height="171px" Width="195px" />

This is code of aspx page, where Image control is defined. Every time a dataset is bound with this image, value in "ImagePath" column of that dataset table will be assigned to ImageUrl property of this image control.


   • Make sure that working directory has got full control for ASPNET user.
   • System.IO namespace allows you to create, modify and delete directories and files. Other related functions are also supported.
   • You can convert Images to binary data and store in database but for sites dealing with larger number of Images, IO Operations method is preferable (which is storing images on WebServer and retrieving them later on using URLs)

Tutorial toolbar:  Tell A Friend  |  Add to favorites  |  Feedback  |