ASP.NET File Handling Tutorial

File with lines of text

An ASP.NET website can handle local files. It can read from, and write to, a text file on the disk. The code can run on any server with file system privileges—and also a local development machine. We read, create and append lines to a file on the disk.

Example

First, this tutorial employs the Global.asax file; you can add this by going to Add New Item... and then Global Application Class. The event handler we focus on is the Application_BeginRequest handler; this is triggered upon every access to the site.

This C# example shows how to handle files in an ASP.NET page. A file is created, read and appended to.

Application that reads and writes file [C#, ASP.NET]

using System;
using System.IO;
using System.Web;

namespace WebApplication2
{
    public class Global : HttpApplication
    {
	protected void Application_BeginRequest(object sender, EventArgs e)
	{
	    // Physical application path.
	    string path = base.Request.PhysicalApplicationPath;

	    // File name.
	    string file = Path.Combine(path, "dates.txt");

	    // Write to file.
	    File.AppendAllLines(file,
		new string[] { DateTime.Now.ToString(), base.Request.Url.ToString(), "<br>" });

	    // Display file.
	    base.Response.WriteFile(file);
	}
    }
}

Output
    (The file will record all requests to the site.)

9/13/2010 3:52:57 PM http://localhost:53770/default.aspx
9/13/2010 3:52:57 PM http://localhost:53770/favicon.ico
9/13/2010 3:52:58 PM http://localhost:53770/default.aspx
9/13/2010 3:52:58 PM http://localhost:53770/favicon.ico
9/13/2010 3:52:59 PM http://localhost:53770/default.aspx 

Using PhysicalApplicationPath. To use files on your ASP.NET website, you need to acquire the directory where the website it stored physically. This will begin at the PhysicalApplicationPath directory. You can get this from the Request object.

PhysicalApplicationPath PropertyPath type

Using Path.Combine. Next, you can append further directories and file names to the root path using the Path.Combine method. You can find more information on the Path type on this site.

Path Examples

Appending lines. There are many ways you can append lines to your text file. In this example, we call File.AppendAllLines with the file name, and also pass a new string[] array containing the time and the file requests. These are reflected in the output.

Using Response.WriteFile. Finally, the file is read in again and written to the response. This method is covered in more detail also on this site.

Response.WriteFile

Summary

The C# programming language

We use the physical path of the website to make reading and writing text files much easier. It is not sufficient to use a hard-coded absolute path if you wish to make the code portable across machines. Additionally, we pointed out some interesting and useful methods you can use to implement a logging mechanism in your ASP.NET website.

ASP.NET Tutorials
.NET