Scott Hanselman

Getting the Line Number and File Name from C#

June 12, '03 Comments [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.

static void Main(string[] args)

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 twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb
Thursday, 18 September 2003 23:30:53 UTC
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.
Mike Rizzi
Friday, 13 June 2003 14:09:03 UTC
Doesn't this only work with assemblies containing Debug information? Also any thoughts on this in context of obfuscated assemblies?
Saturday, 14 June 2003 06:07:42 UTC
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...
Sunday, 15 June 2003 22:41:49 UTC
From the framework 1.0 documentation
Ashish Dave
Friday, 19 September 2003 16:02:09 UTC
Comments are closed.

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