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

Rya*_*n S 11 c# asp.net

我需要两个方法,一个用于从调用异常的位置获取Class,另一个用于获取调用异常的行号.

到目前为止,我有这个代码,它将类名和行号一起给我(例如:DatabaseHandler.cs:第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);
    }
Run Code Online (Sandbox Code Playgroud)

所以如果你有任何想法我怎么能单独得到它们,那将会有很大的帮助.然后将它们传递到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();
    }
Run Code Online (Sandbox Code Playgroud)

这是在特定数据库异常时返回的内容.没有行号被触发的行号或类名.我怎么能得到它?

    Error was found at Class: Oracle.DataAccess.Client.OracleException.     
    Line Number: 0
Run Code Online (Sandbox Code Playgroud)

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

谢谢,瑞恩

Pet*_*PAD 15

你可以这样做

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());
}
Run Code Online (Sandbox Code Playgroud)


Fly*_*179 4

System.Environment.StackTrace。任何时候都有用,而不仅仅是在例外情况下。不过,可能需要使用它进行一些字符串操作;

如果您喜欢高科技一点的东西,您可以使用System.Diagnostics.StackFrame;检查对象浏览器以获取完整的详细信息,但它有查找文件名、行号和列号等的方法。