Reputation: 332
I am executing a method called MethodA, and inside that method, I want to get the line number of MethodA. I can get this number by
var lineNumber = stacktrace.GetFrame(i).GetFileLineNumber()
But, this only gets the line number of the next line that will execute after MethodA. This is problematic when I have a big space between MethodA and the next line of code.
Is there a way to get the previous line of the current line in stacktrace?
edit: MethodA is called in another file on line 100 by this
MethodA();
I want to find line 100
edit:
This error occurs in release mode but it is fine in debug mode
Edit:
So I figured out that i get the correct line number in when uncheck optimize code in build options. However this only works when I debug in release mode; when I just run in release mode, I get the wrong line number.
Upvotes: 1
Views: 360
Reputation: 44295
The previous line is the next frame in the stack. The top of the stack is the current line, the next in line is the previous caller (which is the one you want). A simple loop should grab the info you need:
static void Main(string[] args)
{
MethodA();//called from line 26 on my code
Console.ReadLine();
}
private static void MethodA()
{
var stacktrace = new StackTrace(true);//be sure to pass true to obtain line info
for (int i = 0; i < stacktrace.FrameCount; i++)
{
var frame = stacktrace.GetFrame(i);
Console.WriteLine("{0}, {1}, {2}, {3}", frame.GetFileLineNumber(), frame.GetMethod(), frame.GetFileName(), frame.GetFileColumnNumber());
}
}
OUTPUTS:
35, Void MethodA(), c:\Development\General\Samples\WindowsFormsApplication1\Cons oleApplication1\Program.cs, 13
26, Void Main(System.String[]), c:\Development\General\Samples\WindowsFormsAppli cation1\ConsoleApplication1\Program.cs, 13
Note here the caller is on line 26
Upvotes: 2