Can someone please tell me how to get the line number of the code where the error occurred and display it to the console?
If you want the file and line numbers, you do not need to parse the StackTrace string. You can use System.Diagnostics.StackTrace to create a stack trace from an exception, with this you can enumerate the stack frames and get the filename, line number and column that the exception was raised. Here is a quick and dirty example of how to do this. No error checking included. For this to work a PDB needs to exist with the debug symbols, this is created by default with debug build.
1 using System; 2 using System.Diagnostics; 3 namespace ConsoleApplication1 4 { 5 class Program 6 { 7 static void Main(string[] args) 8 { 9 try 10 { 11 TestFunction(); 12 } 13 catch (Exception ex) 14 { 15 StackTrace st = new StackTrace(ex, true); 16 StackFrame[] frames = st.GetFrames(); 17 18 // Iterate over the frames extracting the information you need 19 foreach (StackFrame frame in frames) 20 { 21 Console.WriteLine("{0}:{1}({2},{3})", frame.GetFileName(), frame.GetMethod().Name, frame.GetFileLineNumber(), frame.GetFileColumnNumber()); 22 } 23 } 24 25 Console.ReadKey(); 26 } 27 28 static void TestFunction() 29 { 30 throw new InvalidOperationException(); 31 } 32 } 33 }
1 catch (Exception ex) 2 { 3 StackTrace st = new StackTrace(ex, true); 4 StackFrame[] frames = st.GetFrames(); 5 string Mssg=""; 6 // Iterate over the frames extracting the information you need 7 foreach (StackFrame frame in frames) 8 { 9 //Console.WriteLine("{0}:{1}({2},{3})", frame.GetFileName(), frame.GetMethod().Name, frame.GetFileLineNumber(), frame.GetFileColumnNumber()); 10 //Mssg =frame.GetFileName(); 11 Mssg=frame.GetMethod().Name; 12 Mssg+="("+frame.GetFileLineNumber()+":"; 13 Mssg += frame.GetFileColumnNumber()+")"; 14 } 15 MessageBox.Show(Mssg.ToString(), "提示"); 16 }
C# 打印出发生错误的文件,方法,代码所在行和列
时间: 2024-10-04 16:07:49