获取异常中的源文件,方法和行

时间:2013-10-09 05:51:46

标签: c# .net exception

我正在尝试从我的c#(4.0)asp.net Web应用程序中发生的异常中获取详细信息。我在bin文件夹中有.pdb文件。以下代码未按预期工作 -

protected void Button1_Click(object sender, EventArgs e)
{
    try
    {
        //throwing Exception
        using (SqlConnection connection=new SqlConnection(""))
        {
            connection.Open();
        }
    }
    catch (Exception exception)
    {
        //Get a StackTrace object for the exception
        StackTrace st = new StackTrace(exception, true);

        //Get the first stack frame
        StackFrame frame = st.GetFrame(0); //returns {PermissionDemand at offset 5316022 in file:line:column <filename unknown>:0:0}

        //Get the file name
        string fileName = frame.GetFileName(); //returns null

        //Get the method name
        string methodName = frame.GetMethod().Name; //returns PermissionDemand

        //Get the line number from the stack frame
        int line = frame.GetFileLineNumber(); //returns 0

        //Get the column number
        int col = frame.GetFileColumnNumber(); //returns 0              
    }
}

这里有什么问题?

更新:        “StackFrame frame = st.GetFrame(st.FrameCount - 1);”解决了这个问题。

1 个答案:

答案 0 :(得分:7)

//Remove this line
StackFrame frame = st.GetFrame(0);

//Add this line
StackFrame frame = st.GetFrame(st.FrameCount - 1);