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

问题描述 投票:1回答:1

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

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

c# .net file io path
1个回答
2
投票

做这个:

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");
© www.soinside.com 2019 - 2024. All rights reserved.