如何显示导致错误的行号,这甚至可以通过 .NET 编译其 .exes 的方式来实现吗?
如果没有,Exception.Message 是否有一种自动化的方式来显示出错的子?
try
{
int x = textbox1.Text;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
如何显示导致错误的行号,这甚至可以通过 .NET 编译其 .exes 的方式来实现吗?
如果没有,Exception.Message 是否有一种自动化的方式来显示出错的子?
try
{
int x = textbox1.Text;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
用于ex.ToString()
获取完整的堆栈跟踪。
即使在发布模式下,您也必须使用调试符号(.pdb 文件)进行编译以获取行号(这是项目构建属性中的一个选项)。
要查看给定异常的堆栈跟踪,请使用e.StackTrace
如果您需要更详细的信息,可以使用System.Diagnostics.StackTrace类(这里有一些代码供您尝试):
try
{
throw new Exception();
}
catch (Exception ex)
{
//Get a StackTrace object for the exception
StackTrace st = new StackTrace(ex, true);
//Get the first stack frame
StackFrame frame = st.GetFrame(0);
//Get the file name
string fileName = frame.GetFileName();
//Get the method name
string methodName = frame.GetMethod().Name;
//Get the line number from the stack frame
int line = frame.GetFileLineNumber();
//Get the column number
int col = frame.GetFileColumnNumber();
}
这仅在有可用于程序集的 pdb 文件时才有效。查看项目属性 - 构建选项卡 - 高级 - 调试信息选择以确保存在 pdb 文件。
如果您使用“StackTrace”并将 .pdb 文件包含在工作目录中,则堆栈跟踪应包含行号。
string lineNumber=e.StackTrace.Substring(e.StackTrace.Length - 7, 7);
这样你就可以从异常中获取行号
public int GetLineNumber(Exception ex)
{
const string lineSearch = ":line ";
var index = ex.StackTrace.LastIndexOf(lineSearch);
int ln=0;
if (index != -1)
{
var lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length);
string lnum = System.Text.RegularExpressions.Regex.Match(lineNumberText, @"\d+").Value;
int.TryParse(lnum,out ln);
}
return ln;
}
如果生成异常的库是使用调试符号编译的,则行号将包含在堆栈跟踪中。这可以是单独的文件 (*.pdb) 或嵌入到库中。
对于 .NET Core、.NET 5 及更高版本,要在发布版本中具有完整的异常行号,请按如下方式配置项目:
<PropertyGroup>
<DebugSymbols>true</DebugSymbols>
<DebugType>embedded</DebugType>
<!-- Only enable the following if the line numbers mismatch -->
<!--<Optimize>false</Optimize>-->
<!--
Additional properties which may impact how printed line numbers match the source code line numbers are listed here:
https://docs.microsoft.com/en-us/dotnet/core/run-time-config/compilation
-->
</PropertyGroup>
上述配置将直接在构建文件中包含调试符号,这些文件可以作为 nugets 发布。
上述方法的替代方法是将调试包与主要的 nuget 包一起恢复,目前尚不支持:https ://github.com/NuGet/Home/issues/9667
现在获取异常行号:
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();
}