C # for script location (csx) of script file

In F #, this is pretty easy with a predefined identifier __SOURCE_DIRECTORY__ https://stackoverflow.com/a/167608/

However, this identifier does not work in C # scripts (csx or C # Interactive files).

> __SOURCE_DIRECTORY __

(1,1): error CS0103: the name "__SOURCE_DIRECTORY__" does not exist in the current context

Getting the current directory in a more traditional way will also not work.

  • Directory.GetCurrentDirectory()

    Returns: C:\Users\$USER_NAME$\

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

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

+4
source share
1 answer

In C #, you can use caller information (available from C # 5 / VS2012). Just declare the method as follows:

string GetCurrentFileName([System.Runtime.CompilerServices.CallerFilePath] string fileName = null)
{
    return fileName;
}

And call it without specifying an optional parameter:

string scriptPath = GetCurrentFileName(); // /path/to/your/script.csx
+3
source

Source: https://habr.com/ru/post/1687438/


All Articles