Tuesday, September 24, 2013

Console.WriteLine() from Your Web Application Pages.

Have you ever thought of doing a Console.WriteLine from your ASP.NET web application page? If possible what is the point in doing so?

The answer to the first question is that, it is possible.

I thought about this after seeing a Stack Overflow question on this, Where does Console.WriteLine go in ASP.NET?.

The answer to this question tells that:
"If you look at the Console class in Reflector, you'll find that if a process doesn't have an associated console, Console.Out and Console.Error are backed by Stream.Null (wrapped inside a TextWriter), which is a dummy implementation of Stream that basically ignores all input, and gives no output."

Yes, it will go to Stream.Null by default and you need to set it to the required Stream  by using Console.SetOut() and you can change the TextWriter by that.

So, let us try this out with a sample:

var fs = new System.IO.FileStream(@"D:\log.txt", System.IO.FileMode.Append);
var tr = new System.IO.StreamWriter(fs);
Console.SetOut(tr);
Console.WriteLine("My Default Debugging");
tr.Close();
fs.Close();

Here in this sample, my TextWriter object tr is set to a FileStream and it is writing to a file D:\log.txt. After that, I am setting my Console to that TextWriter object of tr.

Then, on each of the Console.WriteLine() call in my web page, it will write to the log file D:\log.txt.

Now, it answers the second question as well. What is the point in doing so?

Yes, as shown above, we can very well write logs using this in our web application. All you need is to set your console and call Console.WriteLine(). This makes logging easy from any simple web application.