Scott Hanselman

Getting the Line Number and File Name from C#

June 12, 2003 Comment on this post [5] Posted in Web Services
Sponsored By

Someone wanted to know what the equivalent "preprocessor macros" in C# are for __FILE__ and __LINE__.  They watned to log the current file name and line number.  Note that the "1" as the first parameter to the StackFrame constructor tells it to skip ONE frame up the stack, while the true tells it to capture the file and line info.

[STAThread]
static void Main(string[] args)
{
     ReportError("Yay!");
}

static private void ReportError(string Message)
{
     StackFrame CallStack =
new StackFrame(1, true);
     Console.Write("Error: " + Message + ", File: " + CallStack.GetFileName() + ", Line: " + 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 bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service
September 19, 2003 3:30
The only problem is this code only works in Debug builds. In a production Release build, the file name and line number information doesn't exist. Also, the StackFrame object may be null in a release build, which would NullReferenceException to be thrown at runtime.

Sadly, the StackTrace/StackFrame approach isn't complete replacement for __LINE__ and __FILE__ for someone who needs to report this kind of information in a production Release build.
June 13, 2003 18:09
Doesn't this only work with assemblies containing Debug information? Also any thoughts on this in context of obfuscated assemblies?
June 14, 2003 10:07
True. You're pretty much SOL from what I can tell when in Release or obfuscated. Brent Rector would know all about the obfuscation stuff. Perhaps the Enterprise Instrumentation Framework could step in for more robust tracing...
June 16, 2003 2:41
From the framework 1.0 documentation
September 19, 2003 20:02
test

Comments are closed.

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