Getting the Line Number and File Name from C#

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());
}

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
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.