Apr 23, 2008

Writing Log to Text File with C#

Writing Text File with C#

 

Problem definition : I need to write this for logging for testing purpose. I am logging the information when a aspx file is being called,

I want to put all information like browser, os, resolution, referer page etc.

 

So here we goes

I like to add a method let it call LogToFile()

Don't forget to include #using System.IO; as we are going to use stream writer

protected void LogToFile()

    {

            string logFilePath = Server.MapPath("Trace.txt");

        StreamWriter sw = new StreamWriter(logFilePath, true);

        //true means if file not there then create it otherwise append to it.

        try

        {

            sw.WriteLine("Logging Time: " + DateTime.Now.ToLongDateString());

            sw.WriteLine("OS/Browser/Version : "+Request.Browser.Platform.ToString()+"/" +Request.Browser.Browser.ToString()+ “/"+Request.Browser.Version.ToString());

           

            if (Request.UrlReferrer != null)

            {

                sw.WriteLine("Referrer: "+ Request.UrlReferrer.ToString());

            }

            sw.WriteLine("User Agent: " + Request.UserAgent.ToString());

            sw.WriteLine("--------------------------------------------------------");

        }

        catch(Exception )

        {

        }

        finally

        {

            if (sw != null)

            {

                sw.Close();

            }

        } 

    }

Now call this function into pageload method of your page... you will get the trace.

You can add more properties/ information according to your needs.