C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Communities   Interview   Jobs   Projects   Offshore Development    
Silverlight Tutorials | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Revenue Sharing |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...

New Feature: Community Sites: Create your own .NET community website and start earning from Google AdSense ! It's Free !






Writing Text File with C#


Posted Date: 03 Jul 2008    Resource Type: Code Snippets    Category: C# Syntax
Author: M. IrfanMember Level: Gold    
Rating: Points: 5



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




Responses

Author: siva    08 Jul 2008Member Level: Silver   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


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: DataTable in C#
Previous Resource: Small sample methods on LINQ
Return to Discussion Resource Index
Post New Resource
Category: C# Syntax


Post resources and earn money!
 
Related Resources



dotNet Slackers   BizTalk Adaptors    Web Design


Contact Us    Privacy Policy    Terms Of Use