TheDeveloperBlog.com

Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

ASP.NET File Handling Tutorial

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

File. 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.

Note: This tutorial shows how to read local files from the disk and process them on an ASP.NET website.

Example. First, we use 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.

Application_BeginRequest

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

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

namespace WebApplication1
{
    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 is physically stored. This begins at the PhysicalApplicationPath directory. We get this from the Request object.

PhysicalApplicationPath

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 string array containing the time and the file requests.

FileString Array

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. 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.

Also: We pointed out some interesting and useful methods you can use to implement a logging mechanism in your ASP.NET website.