ASP.NET File HandlingHandle files in an ASP.NET page. Create a file, read a file, and append to a file.
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.
PhysicalApplicationPath This returns the directory where the website is physically stored. We get this from the Request object.
Path.Combine Next, you can append further directories and file names to the root path using the Path.Combine method.
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.
Finally The file is read in again and written to the response. This method is covered in more detail also on this site.
ASP.NET program that reads and writes file
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); } } }
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
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.
© 2007-2022 sam allen.
see site info on the changelog.