11

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 line number during application run in VB.net

Which mentions "you always need to include the PDB file with your code, which contains debugging information that is used in situations like this". Under advanced compiler settings I've tried "Generate debug info" as "pdb-only" and "full" for my release build and confirmed that a fresh PDB file is generated in the same directory as my EXE. However the following test code generates a line number of zero for each stack frame and doesn't return a filename:

    Dim st As StackTrace = New StackTrace(ex)
    For Each sf As StackFrame In st.GetFrames
        MsgBox("Line " & sf.GetFileLineNumber() & sf.GetFileName)
    Next

However the following code straight after it generates an otherwise good looking stack trace so it doesn't seem to be a problem with the exception handler in general:

ExceptionDetails.Text = ex.GetType.ToString & "(0x" & hr.ToString("X8") & "): " & ex.Message & vbCrLf & ex.StackTrace

I can't seem to find any other likely settings under the project configuration and wondered if anyone had ideas on other things that may cause this problem. All the solutions I've found searching here and elsewhere just seem to suggest making sure the PDB is in the same path as the executable.

4

3 回答 3

15

这个问题已经解决了一段时间,但我想我会分享我最近在我的项目中包含的最终工作功能。它返回初始异常信息和该点的完整堆栈跟踪,后跟从堆栈跟踪导致异常的行号和文件名。

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
于 2014-03-11T23:19:07.213 回答
5

从您正在调用的构造函数的文档中:

StackTrace 是使用调用者的当前线程创建的,不包含文件名、行号或列信息。

尝试使用:

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

相反,它使用这个构造函数。第二个构造函数参数描述为:

true 捕获文件名、行号和列号;否则为假。

于 2012-12-27T00:37:16.827 回答
1

尝试使用

public StackTrace(Exception e, bool fNeedFileInfo);

构造函数并将 fNeedFileInfo 设置为 true

于 2012-12-27T00:39:03.163 回答