I'm trying to obtain line numbers to create a debug log, hoping to more easily plot a path through code function calls etc
However if I am using StackTrace correctly it is not giving the response I needed:
Private Sub FormAnalyser_Load(sender As Object, e As EventArgs) Handles MyBase.Load
...
If isDebug Then LogDebugCall("analyser.vb", "_queryBuilder.Load()")
_queryBuilder.Load()
...
End Sub
In Debugger.vb class.
Public Shared Sub LogDebugCall(docName As String, callStatement As String)
Debug.Indent()
Debug.Indent()
Debug.Indent()
Dim st As New StackTrace(True)
Dim sf As StackFrame = st.GetFrame(st.FrameCount - 1)
Dim line As String
line = "Line: " & CStr(sf.GetFileLineNumber())
Dim tmp As String
tmp = sf.GetMethod().Name
Debug.WriteLine(callStatement & Space(50 - Len(callStatement)) & "(Call: " & callStatement & " " & docName & " " & line & ")")
...
End sub
So I always get LineNUmber of 0 although the FrameCount might be 58 or whatever depending at what point it is called. INspection of sf gives - sf {ThreadStart at offset 68 in file:line:column :0:0 } System.Diagnostics.StackFrame and there is an OFFSET_UNKNOWN flag -1 There is a thread here that shows setting of debug_info which I have not done, but cant find this setting in VS community 2013. Is this the cause of my woes or am I just using it wrongly?
As this is still not giving me anything usefull and having read here. I simplified the structure just for test puposes that the method suggested there but moved it to my form class directly.
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
Exception wasnt suitable as I want it when there is no exception so
Public Sub PrintCurrentLine()
Dim st As StackTrace = New StackTrace(true)
Dim sf As StackFrame = st.GetFrame(st.FrameCount - 1)
Console.WriteLine("Line " & sf.GetFileLineNumber())
End Sub
Not working! Value returned in both instances -1 So I declared st,sf directly in the calling method whose line number I want to catch and sf.GetFileLineNumber() still returns -1 So if anybody else has anything else to throw at me I would appreciate it!
Thanks guys!
Ok SO I got to the answer and obtaining the linenumbers were not so difficult in the end. I am implementing a call to my debugger class in each method: debugger.MethodIn() the frame sf represents that method with the debugger call, and sfCaller represents the the method that called that method.
Dim st As New StackTrace(True)
Dim sf As StackFrame
Dim sfCaller As StackFrame
sf = st.GetFrame(1)
sfCaller = st.GetFrame(2)
col = sfCaller.GetFileLineNumber
ln = sfCaller.GetFileColumnNumber