Log a String Collection in .NET

I was working on a .NET 4 standalone application and wanted to write a simple routine to log messages to a text file for later analysis. Here’s how I created a List<string> and wrote it to a Log file using the File.WriteAllLines method. The WriteAllLines method creates a new file, writes a collection of strings to the file, and then closes the file. If the file already exists, it is overwritten, but you can get around this by creating random time-stamped file names.

In the code shown below, we add a few items to the List<String> depicting Info, Errors and Warning messages. We then use the WriteAllLines method and a simple expression to filter out ‘Info’ messages and write it to a log file.

static void Main(string[] args)
{
try
{
List<string> strmsg = new List<string>();
// Sample Log messages
strmsg.Add("Info: Customer Record Added");
strmsg.Add("Warning: Disallowed operations");
strmsg.Add("Info: User Logged in");
strmsg.Add("Error: Incorrect Customer");
strmsg.Add("Info: Email Sent to the User");

// write all Info messages to the log file
File.WriteAllLines(@"C:\Logs\info.log",
strmsg.Where(s => s.StartsWith("Info:")).ToArray());
Console.WriteLine("Info Log Created");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

Console.ReadLine();
}

Note: If you are using .NET Framework 3.5 or earlier, you will have to convert the IEnumerable<string> to an array, as .NET 3.5 does not have an overloaded method that accepts an IEnumerable<string>. In .NET 3.5, use the following piece of code:

File.WriteAllLines(@"C:\Logs\info.log",
strmsg.Where(s => s.StartsWith("Info:")).ToArray())

OUTPUT

image






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: