c#命令行没有错误行号

c# commandline no error line number

如果 .NET 代码中存在异常并且 PDB 文件可用,您通常会收到异常消息中显示的源代码行号错误。这在命令行可执行文件中似乎有所不同,尽管 PDB 文件可用,但我没有得到任何行号:

Anwendung: MNX.CommandLine.EpkFtpEventhandler.exe Frameworkversion: v4.0.30319 Beschreibung: Der Prozess wurde aufgrund eines Ausnahmefehlers beendet. Ausnahmeinformationen: System.Data.SqlClient.SqlException Stapel: bei System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(System.String, Boolean, Int32, Boolean) bei System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(System.Threading.Tasks.TaskCompletionSource`1, System.String, Boolean, Int32, Boolean) bei System.Data.SqlClient.SqlCommand.ExecuteNonQuery() bei MNX.DB.WriteLocal(System.String) bei MNX.DB.Write(System.String) bei MNX.CommandLine.EpkFtpEventHandler.Main(System.String[])

有人知道为什么吗?

尝试通过访问 Debug > Options > Debugging > Symbols 清空符号缓存,然后清理您的解决方案。

使用 Stack Frames 并用 try catch 包围你的代码:

try
{
     throw new Exception();
}
catch (Exception ex)
{
    // Get stack trace for the exception with source file information
    var st = new StackTrace(ex, true);
    // Get the top stack frame
    var frame = st.GetFrame(0);
    // Get the line number from the stack frame
    var line = frame.GetFileLineNumber();
    // Print the line number
    Console.WriteLine($"An Error ({ex.Message}) occurred in line {line}");
}

为了避免抄袭:我的想法来自 this question

我不知道为什么它通常不会显示在您的控制台应用程序中,但这也应该显示。

Exception.StackTrace 返回了行号,当它来自捕获时。奇怪的是只有当我捕获异常时,而不是当它被抛出而没有被捕获时。