C# – 调用异常时如何获取类名和行号

我需要两种方法,一种是从调用异常的方法获取Class,另一种方法得到调用异常的行号.

到目前为止,我有这个代码,它让我的类名和行号一起(例如:DatabaseHandler.cs:line 70):

private string GetClassAndLine()
    {
        string tempName = e.GetBaseException().ToString();
        int tempPosition = 0;
        int length = tempName.Length;
        for (int i = 0; i < length; i++)
        {
            if (tempName.ElementAt(i).Equals('\\'))
            {
                tempPosition = i + 1;
            }
        }
        return tempName.Substring(tempPosition,length - tempPosition);
    }

所以,如果你有任何想法,我可以个别地让他们,这将是很大的帮助.然后将它们传递到Oracle中以存储发生的任何异常.

更新2:

我正在测试这个代码,有些建议:

private string GetClassName()
    {
        System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(e,true); 
        return trace.GetFrame(0).getmethod().ReflectedType.FullName;
    }

    private int GetLineNumber()
    {
        System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(e,true); 
        return trace.GetFrame(0).GetFileLineNumber();
    }

这是特定的数据库异常返回的.没有线号或类名被触发.我该怎么做?

Error was found at Class: Oracle.DataAccess.Client.OracleException.     
    Line Number: 0

我想要的是例如:“Class:Logging.cs,Line:57”

谢谢,
瑞安

解决方法

你可以这样做
try
{
    // Some code that can cause an exception.

    throw new Exception("An error has happened");
}
catch (Exception ex)
{
    System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex,true);

    Console.WriteLine(trace.GetFrame(0).getmethod().ReflectedType.FullName);
    Console.WriteLine("Line: " + trace.GetFrame(0).GetFileLineNumber());
    Console.WriteLine("Column: " + trace.GetFrame(0).GetFileColumnNumber());
}

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...