Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# for scripting (csx) location of script file

Tags:

c#

roslyn

csx

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\

like image 415
Pawel Troka Avatar asked Oct 13 '17 11:10

Pawel Troka


2 Answers

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
like image 68
Thomas Levesque Avatar answered Oct 17 '22 20:10

Thomas Levesque


In csx, you are can add ExecutionContext as a parameter and access FunctionDirectory from it like so:

using System;
using Microsoft.Azure.WebJobs;

public static void Run(TimerInfo myTimer, ExecutionContext executionContext, ILogger log) {
    var dir = executionContext.FunctionDirectory;

    log.LogInformation($"Directory: {dir}");
}

ExecutionContext.FunctionDirectory will return the directory the contains the function's function.json file. It doesn't include the trailing .

At this time this seems to be the best documentation for ExecutionContext.


I am trying to find the answer to this question myself, and this was my previous answer.

In csx, the following helper method will return the directory "of the source file that contains the caller".

using System.IO;

...

public static string CallerDirectory([System.Runtime.CompilerServices.CallerFilePath] string fileName = null)
{
    return Path.GetDirectoryName(fileName);
}

To call it, don't specify the fileName parameter.

var dir = CallerDirectory();
like image 1
Adrian Toman Avatar answered Oct 17 '22 21:10

Adrian Toman