Use the StackFrame.GetFileLineNumber method, for example:
private static void ReportError(string message) { StackFrame callStack = new StackFrame(1, true); MessageBox.Show("Error: " + message + ", File: " + callStack.GetFileName() + ", Line: " + callStack.GetFileLineNumber()); }
See Scott Hanselman's Blog Entry for more information.
[Edit: Added the following]
For those using .Net 4.5 or later , consider the CallerFilePath , CallerMethodName, and CallerLineNumber attributes in the System.Runtime.CompilerServices namespace. For example:
public void TraceMessage(string message, [CallerMemberName] string callingMethod = "", [CallerFilePath] string callingFilePath = "", [CallerLineNumber] int callingFileLineNumber = 0) {
The arguments must be string for CallerMemberName and CallerFilePath and int for CallerLineNumber and must have a default value. Specifying these attributes in the method parameters tells the compiler to insert the corresponding value into the calling code at compile time, which means that it works through obfuscation. See Caller Information for more information.
akton Sep 23 '12 at 22:26 2012-09-23 22:26
source share