C# 用于脚本文件的脚本 (csx) 位置

Paw*_*oka 5 c# roslyn

在 F# 中使用预定义标识符相当容易__SOURCE_DIRECTORY__ /sf/answers/340272061/

但是,此标识符在 C# 脚本(csx 文件或 C# Interactive)中不起作用。

> __SOURCE_DIRECTORY__

(1,1): 错误 CS0103: 当前上下文中不存在名称“__SOURCE_DIRECTORY__”

以更传统的方式获取当前目录也行不通。

  1. Directory.GetCurrentDirectory()

    返回: C:\Users\$USER_NAME$\

  2. new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath;

    返回: C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\ManagedLanguages\VBCSharp\InteractiveComponents\

Tho*_*que 10

在 C# 中,您可以利用调用者信息属性(自 C# 5 / VS2012 起可用)。只需声明一个这样的方法:

string GetCurrentFileName([System.Runtime.CompilerServices.CallerFilePath] string fileName = null)
{
    return fileName;
}
Run Code Online (Sandbox Code Playgroud)

并在不指定可选参数的情况下调用它:

string scriptPath = GetCurrentFileName(); // /path/to/your/script.csx
Run Code Online (Sandbox Code Playgroud)

  • 这对我不起作用。我尝试在 .csx 文件以及从 .csx 引用的程序集中定义此函数,两个版本都返回空字符串。 (2认同)