8

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\

Adrian Toman
  • 11,316
  • 5
  • 48
  • 62
Pawel Troka
  • 853
  • 2
  • 12
  • 33

2 Answers2

9

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
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • 1
    This doesn't work for me. I tried defining this function in the .csx file as well as in an assembly which I referenced from the .csx and both versions return an empty string. – odkken Mar 05 '19 at 19:43
1

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();
Adrian Toman
  • 11,316
  • 5
  • 48
  • 62