How to get the path to the .csx script being executed?

693 Views Asked by At

When executing a C# script (.csx) with C:\Program Files (x86)\MSBuild\14.0\Bin\amd64\csi.exe, how do I get the path to the script being executed?

The line

Console.WriteLine(AppDomain.CurrentDomain.BaseDirectory); 

prints the path to the interpreter (csi.exe), not the script.

The script should be aware of it's path at some level, as you can load assemblies with a relative path like this:

#r "..\\bla\\asdf.dll"
1

There are 1 best solutions below

0
On

Only by using a helper method, could I programatically obtain the full path to the .CSX source script. The method uses the CallerFilePath attribute. This works from inside the interactive Rosalyn C# shell, as well as command line.

using System.Runtime.CompilerServices;
// Work-around helper method to get the source file location.
private static string GetSourceFile([CallerFilePath] string file = "") => file;
Console.WriteLine($"Full path to .csx source file => {GetSourceFile()}");