簡體   English   中英

引發異常時從stacktrace和frame獲取文件名

[英]Get the filename from stacktrace and frame when throw an exception

引發異常時,我試圖獲取文件名和源代碼號。 但是我什么都沒有。

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();
        }
    }
}

只有一幀可用。 所以我在GetFrame(index)使用索引0。

我將編寫一個方法並使用CallerFilePathCallerLineNumberCallerMemberName屬性

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

用法: Log()

有關更多信息: https : //msdn.microsoft.com/zh-cn/library/hh534540.aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM