您的位置:首页 > 编程语言 > C#

C# 打印出发生错误的文件,方法,代码所在行和列

2014-06-19 17:29 477 查看
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.

using System;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
TestFunction();
}
catch (Exception ex)
{
StackTrace st = new StackTrace(ex, true);
StackFrame[] frames = st.GetFrames();

// Iterate over the frames extracting the information you need
foreach (StackFrame frame in frames)
{
Console.WriteLine("{0}:{1}({2},{3})", frame.GetFileName(), frame.GetMethod().Name, frame.GetFileLineNumber(), frame.GetFileColumnNumber());
}
}

Console.ReadKey();
}

static void TestFunction()
{
throw new InvalidOperationException();
}
}
}


catch (Exception ex)
{
StackTrace st = new StackTrace(ex, true);
StackFrame[] frames = st.GetFrames();
string Mssg="";
// Iterate over the frames extracting the information you need
foreach (StackFrame frame in frames)
{
//Console.WriteLine("{0}:{1}({2},{3})", frame.GetFileName(), frame.GetMethod().Name, frame.GetFileLineNumber(), frame.GetFileColumnNumber());
//Mssg =frame.GetFileName();
Mssg=frame.GetMethod().Name;
Mssg+="("+frame.GetFileLineNumber()+":";
Mssg += frame.GetFileColumnNumber()+")";
}
MessageBox.Show(Mssg.ToString(), "提示");
}




http://stackoverflow.com/questions/2723607/exception-handling-display-line-number-where-error-occurred

http://208.71.46.190/search/srpcache?ei=UTF-8&p=C%23+error+code+line+num&fr=yfp-t-950&u=http://cc.bingj.com/cache.aspx?q=C%23+error+code+line+num&d=4975892695745249&mkt=en-US&setlang=en-US&w=8LK2LxEPWkHWxjo07q5TTWPArOhQfQ6u&icp=1&.intl=us&sig=AJMgmyuWl4twmW4AURZ0Dg--
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐