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, September 18, 2003 11:30:53 PM 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, June 13, 2003 2:09:03 PM UTC
Doesn't this only work with assemblies containing Debug information? Also any thoughts on this in context of obfuscated assemblies?
Saturday, June 14, 2003 6:07:42 AM 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, June 15, 2003 10:41:49 PM UTC
From the framework 1.0 documentation
Ashish Dave
Friday, September 19, 2003 4:02:09 PM 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.