Sairama's Interesting Code of the Day - Printing Line Numbers while Debugging C#
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.
About Newsletter
Comments are closed.