Get the filename from stacktrace and frame when th

2019-02-27 21:32发布

问题:

I tried to get the filename and sourceline number when an exception is thrown. But I got nothing.

class Program
{
    static void Main(string[] args)
    {
        try
        {
            throw new InvalidOperationException();
        }
        catch (InvalidOperationException exception)
        {
            var stackTrace = new StackTrace(exception);
            var currentFrame = stackTrace.GetFrame(0);
            var fileName = currentFrame.GetFileName();
            var sourceLineNumber = currentFrame.GetFileLineNumber();
            Console.WriteLine("File Name: " + fileName);
            Console.WriteLine("Source line number: " + sourceLineNumber);
            Console.ReadKey();
        }
    }
}

There is only one frame is available. So I use the index 0 in GetFrame(index).

回答1:

I would write a method and use CallerFilePath, CallerLineNumber and CallerMemberName attributes

public void Log([CallerFilePath]string path="",[CallerLineNumber]int lineNumber=0,[CallerMemberName] string memberName="")
{
    Console.WriteLine(path + " " + lineNumber + " " + memberName);
}

Usage: Log()

For more Info: https://msdn.microsoft.com/en-us/library/hh534540.aspx