I would like to print out my debug message with line number in VB.net application. I did like this,
Dim st As StackTrace
Dim sf As StackFramee
st = New StackTrac
After reading the several answers I came for me to the following solution as equivalent to the C++ macro LINE
(New StackTrace(New StackFrame(True))).GetFrame(0).GetFileLineNumber())
which can be used for example as:
Console.WriteLine(String.Format("Executed on line# {0}", (New StackTrace(New StackFrame(True))).GetFrame(0).GetFileLineNumber()))
The compiled assemblies will not have line numbers associated with them. This is not information that is part of the assemblies.
The information is kept in the debugging symbols file - the pdb
file.
From MSDN - StackTrace class:
StackTrace information will be most informative with Debug build configurations. By default, Debug builds include debug symbols, while Release builds do not. The debug symbols contain most of the file, method name, line number, and column information used in constructing StackFrame and StackTrace objects.
The code you've shown is working exactly as expected. It's printing the number of the line where you captured the stack frame. Because you've defined it in a different class, it's printing the line number of the file that contains that class.
The GetFrame
method is important here. Stack frames are numbered starting at 0, which is the last stack frame pushed. So, by referring to frame 0, you are instructing the runtime to print the line number of the last stack frame that was pushed. When one method calls another, a new stack frame is created.
Instead, you need to change your method in a couple of important ways. First, you need to get the first frame that was pushed onto the stack. And second, you probably want to accept a parameter containing information about the exception that you are responding to. Try rewriting your debug method to look something like this:
Public Sub PrintCurrentLine(ByVal ex As Exception)
Dim st As StackTrace = New StackTrace(ex)
Dim sf As StackFrame = st.GetFrame(st.FrameCount - 1)
Console.WriteLine("Line " & sf.GetFileLineNumber())
End Sub
Also remember that if you're running the code with optimizations enabled, things like line numbers may have changed. You always need to include the PDB file with your code, which contains debugging information that is used in situations like this. It maps the optimized code back to your original source.