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 go:
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.
For more details, visit http://matespoint.blogspot.com/2008/04/writing-log-to-text-file-with-c.html
|
| Author: siva 08 Jul 2008 | Member Level: Bronze Points : 1 |
Hello Nice piece of code Thanks for sharing your knowledge with us. I hope to see more good code from your side This code will help lots of guys Thanks to you Regards, Siva
|