2011-02-04 70 views
2

我有寫日誌爲.txt文件執行代碼時有沒有辦法獲得當前行號? C#

Helper.WriteSimpleDebugTrace(securityLogFilePath, "About to authenticate user."); 
Helper.WriteSimpleDebugTrace(securityLogFilePath, "Directory Search Path:"); 
Helper.WriteSimpleDebugTrace(securityLogFilePath, "Username:" + username); 

我只是想知道一個應用是有辦法,我可以通過當前的行號到這種方法嗎?

+1

Environment.StackTrace會給你整個stacetrace。也許解析它。由於這是一項昂貴的操作,您會希望對此非常小心。如果您發佈沒有pdbs的代碼,那麼這將不適用於生產。 ETA:http://peterkellner.net/2009/12/21/how-to-get-a-stack-trace-from-c-without-throwing-exception/有一個獲取特定幀行號的例子。 – Sean 2011-02-04 17:09:33

+1

Scott Hanselman寫了一篇簡短的[博客文章](http://www.hanselman.com/blog/GettingTheLineNumberAndFileNameFromC.aspx)關於這個 – Cameron 2011-02-04 17:11:49

+0

肖恩 - 爲什麼你不加這個作爲答案?我不能將它標記爲答案:-)感謝您的信息。 – Exitos 2011-02-04 17:12:51

回答

2

你可能想要類似下面的方法。 Conditional屬性將導致對此方法的所有調用在非調試版本中都會編譯爲無。然後,如果您抓取StackFrame 1而不是0,則會獲得有關調用DebugPrintTrace的地方的信息。

[Conditional("DEBUG")] 
    public static void DebugPrintTrace(string message) 
    { 
     StackTrace stackTrace = new StackTrace(true); 
     StackFrame sf = stackTrace.GetFrame(1); 
     Console.WriteLine("Trace " 
      + sf.GetMethod().Name + " " 
      + sf.GetFileName() + ":" 
      + sf.GetFileLineNumber() + Enviroment.NewLine); 

     Console.WriteLine(message + Enviroment.NewLine); 


    } 

更重要的是還添加了condtitional 「DEBUG」 你WriteSimpleDebugTrace

相關問題