在exception处理中显示行号

如何显示哪个行号导致错误,这是否可能与.NET编译其.exes的方式有关?

如果没有,Exception.Message是否有自动方式显示被淘汰的子?

try { int x = textbox1.Text; } catch(Exception ex) { MessageBox.Show(ex.Message); } 

使用ex.ToString()获取完整的堆栈跟踪。

您必须使用调试符号(.pdb文件)进行编译,即使在发布模式下也可以获取行号(这是项目构建属性中的一个选项)。

要查看给定Exception的堆栈跟踪 ,请使用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);