如何获取当前 C# 源代码文件的路径?

Jam*_* Ko 7 .net c# io file path

如何获取当前 C# 源代码文件的路径,或文件存储的目录?(我自己回答这个问题,因为我在 Google 搜索中没有找到任何内容。)

注意:这不是要求Assembly.GetEntryAssembly().Location,它给出了可执行文件的路径,也不是Directory.GetCurrentDirectory(),它给出了调用进程的目录。)

Jam*_* Ko 11

做这个:

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

How it works: Roslyn specially recognizes the CallerFilePath, CallerLineNumber, and CallerMemberName attributes (the last one might look familiar to you if you've done some MVVM programming). At compile-time, it populates parameters marked with these attributes with the actual file path / line number / member name of the caller. If you compile and decompile the above code, the assignment to path will look like

var path = GetThisFilePath(@"path\to\your\source\code\file.cs");
Run Code Online (Sandbox Code Playgroud)