Scott Hanselman

Sairama's Interesting Code of the Day - Printing Line Numbers while Debugging C#

February 19, '03 Comments [1] Posted in Web Services
Sponsored By

In C++ if problems happen, we'll want to log the error along with filename and Line Numbers, often like:

CString strCompleteMessage;
strCompleteMessage.Format(_T("%s , HRESULT %0x [%s,%d]"),strMessage,hr,A2W(__FILE__),__LINE__);
LogInfo(strCompleteMessage);

In C#, there are no such macros so we use the StackFrame class. Below we show how to print the filename and line numbers while logging messages/errors.

     public static void foo()
     {
     // some operations here
     // some error here
     string msg = "Unable to do xyz operation, Please report this to abc@xyz.com";

     // true means get the file information also ( needs pdb files which can be generated for Release builds )

     StackFrame CallStack = new StackFrame(0, true);
     Console.WriteLine("Error:{0} occurred in:{1} in File: {2} at Line: {3}", msg, CallStack.GetMethod(), CallStack.GetFileName(), CallStack.GetFileLineNumber() );
}

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web
Thursday, February 20, 2003 6:45:53 PM UTC
Cool, I had no idea you could do this. From the help, it looks like this info wouldn't work in a release build, or at least w/o the symbols available. Maybe this should be surrounded with a #if DEBUG?
Comments are closed.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.