Is it possible to read File from same folder where Azure function exists

Anirudha Gupta picture Anirudha Gupta · Apr 1, 2018 · Viewed 17.6k times · Source

In my Azure C# function I need to read a .txt file. I make the .txt file in Visual studio and set it to "copy Always".

Now I am using this code to read the file

var dir = System.IO.Path.GetDirectoryName(
    System.Reflection.Assembly.GetEntryAssembly().Location);

var path = System.IO.Path.Combine(dir, "twinkle.txt");

this code doesn't work. When I open the folder which is the value of dir. It lead me to this directory ""C:\Users{username}\AppData\Local\Azure.Functions.Cli\1.0.9""

How I can store a simple txt file in Azure function. Or I need Azure Storage for this.

Anything else I can do to get this done.

Update for showing file copied

enter image description here

Answer

Mikhail Shilkov picture Mikhail Shilkov · Apr 1, 2018

Here is how to get to the correct folder:

public static HttpResponseMessage Run(HttpRequestMessage req, ExecutionContext context)
{
    var path = System.IO.Path.Combine(context.FunctionDirectory, "twinkle.txt");
    // ...
}

This gets you to the folder with function.json file. If you need to get to bin folder, you probably need to go 1 level up, and then append bin:

// One level up
Path.GetFullPath(Path.Combine(context.FunctionDirectory, "..\\twinkle.txt"))

// Bin folder
Path.GetFullPath(Path.Combine(context.FunctionDirectory, "..\\bin\\twinkle.txt"))