Getting VB.NET line numbers in stack trace

后端 未结 3 802
北海茫月
北海茫月 2020-12-30 09:39

I have a VB.NET 2010 Winforms application where I\'d like to include line numbers in the stack trace. I\'ve read the following question and answers:

how to print out

相关标签:
3条回答
  • 2020-12-30 10:06

    This question was solved some time back but I thought I'd share the final working function that I've been including in my projects recently. It returns the initial exception information and full stack trace at that point followed by the line numbers and filenames leading up to the exception from the stack trace.

    Public Function GetExceptionInfo(ex As Exception) As String
        Dim Result As String
        Dim hr As Integer = Runtime.InteropServices.Marshal.GetHRForException(ex)
        Result = ex.GetType.ToString & "(0x" & hr.ToString("X8") & "): " & ex.Message & Environment.NewLine & ex.StackTrace & Environment.NewLine
        Dim st As StackTrace = New StackTrace(ex, True)
        For Each sf As StackFrame In st.GetFrames
            If sf.GetFileLineNumber() > 0 Then
                Result &= "Line:" & sf.GetFileLineNumber() & " Filename: " & IO.Path.GetFileName(sf.GetFileName) & Environment.NewLine
            End If
        Next
        Return Result
    End Function
    
    0 讨论(0)
  • 2020-12-30 10:16

    From the documentation of the constructor you're calling:

    The StackTrace is created with the caller's current thread, and does not contain file name, line number, or column information.

    Try using:

    Dim st As StackTrace = New StackTrace(ex, True)
    

    instead, which uses this constructor. The second constructor parameter is described as:

    true to capture the file name, line number, and column number; otherwise, false.

    0 讨论(0)
  • 2020-12-30 10:25

    Try using the

    public StackTrace(Exception e, bool fNeedFileInfo);
    

    Constructor and setting fNeedFileInfo to true

    0 讨论(0)
提交回复
热议问题