簡體   English   中英

如何獲取當前C#源代碼文件的路徑?

[英]How do I get the path to the current C# source code file?

如何獲取當前C#源代碼文件的路徑或該文件存儲的目錄? (我自己回答了這個問題,因為我沒有通過Google搜索找到任何內容。)

注意:這不是要求Assembly.GetEntryAssembly().Location ,它提供了可執行文件的路徑,也不是Directory.GetCurrentDirectory() ,它提供了從中調用過程的目錄。)

做這個:

using System.Runtime.CompilerServices;

private static string GetThisFilePath([CallerFilePath] string path = null)
{
    return path;
}

var path = GetThisFilePath(); // path = @"path\to\your\source\code\file.cs"
var directory = Path.GetDirectoryName(path); // directory = @"path\to\your\source\code"

工作原理: Roslyn特別識別CallerFilePathCallerLineNumberCallerMemberName屬性(如果您已完成一些MVVM編程,則最后一個可能看起來很熟悉)。 在編譯時,它將使用調用者的實際文件路徑/行號/成員名填充標有這些屬性的參數。 如果編譯和反編譯以上代碼,則對path的分配將類似於

var path = GetThisFilePath(@"path\to\your\source\code\file.cs");

暫無
暫無

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

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