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

六月ゝ 毕业季﹏ 提交于 2021-02-06 01:35:52

问题


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


回答1:


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"))



回答2:


For those like me who doesn't have access to ExecutionContext since we have to read a file in Startup.

var binDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var rootDirectory = Path.GetFullPath(Path.Combine(binDirectory, ".."));

///then you can read the file as you would expect yew!
File.ReadAllText(rootDirectory + "/path/to/file.ext");

Also worth noting that Environment.CurrentDirectory might work on a local environment, but will not work when deployed to Azure.

Works inside functions too.

Reference




回答3:


Here is a useful link: https://github.com/Azure/azure-functions-host/wiki/Retrieving-information-about-the-currently-running-function

There is the possibility of a hard coded way:

File.ReadAllText("d:\home\site\wwwroot\NameOfYourFunction" + "/path/to/file.ext");


来源:https://stackoverflow.com/questions/49597721/is-it-possible-to-read-file-from-same-folder-where-azure-function-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!