Search code examples
c#roslyncsx

C# for scripting (csx) location of script file


In F# it's rather easy with predefined identifier __SOURCE_DIRECTORY__ https://stackoverflow.com/a/4861029/2583080

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

> __SOURCE_DIRECTORY__

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

Getting current directory in more traditional way will not work either.

  1. Directory.GetCurrentDirectory()

    Returns: C:\Users\$USER_NAME$\

  2. 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\


Solution

  • In C# you can take advantage of caller information attributes (available since C# 5 / VS2012). Just declare a method like this:

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

    And call it without specifying the optional parameter:

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