Skip to content

Logging From an ASP.NET 2.0 Application to a Local File

Updated: at 11:17 PM

(User MapPath and FileStream Together)

A very common scenario we often run into is we need to log some information to a local text file on the web server.  We know we can use all the health monitoring capabilities built in to asp.net for reasons like performance,
standards, best practices, etc., but sometimes, you just want to log something right now and you don't want to spend a lot of time.

So, Here is a very very simple version that does that and is 100% reliable.  Basically, say you wanted to simply log the useragent from a request to a file called ~/App_Data/UserAgents.txt.  Here is some simple code to do that.

    1 using System;

    2 using System.Data;

    3 using System.Configuration;

    4 using System.Collections;

    5 using System.Web;

    6 using System.Web.Security;

    7 using System.Web.UI;

    8 using System.Web.UI.WebControls;

    9 using System.Web.UI.WebControls.WebParts;

   10 using System.Web.UI.HtmlControls;

   11 

   12 public partial class Default2 : System.Web.UI.Page

   13 {

   14 

   15     public static Object synchronizeVariable = "locking";

   16 

   17     protected void Page_Load(object sender, EventArgs e)

   18     {

   19         String fileName = Context.Server.MapPath("~") +

   20             "\\App_Data\\UserAgents.txt";

   21         lock (synchronizeVariable)

   22         {

   23             StreamWriter sw = new StreamWriter(fileName, true);

   24             sw.WriteLine(DateTime.Now);

   25             sw.WriteLine(Request.UserAgent);

   26             sw.Close();

   27         }

   28     }

   29 }

Just to be safe, we added a lock around the file write code.  This way, if two processes come in at the same time, they will both write out correctly. Again, this is very crude, not very efficient or elegant, but very clean and
reliable.  Just don't mention you got it from me!