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
It's possible for multiple function apps to share the same storage account without any issues. For example, in Visual Studio you can develop multiple apps using the Azure Storage Emulator.
ExecutionContext. The execution context enables interaction with the Azure Functions execution environment. HttpRequestMessage<T> An HttpRequestMessage instance is provided to Azure functions that use HttpTrigger.
Click on the Go button on the Advanced Tools window as shown below. You can able to see Debug console DropDown on the top of the page, select the CMD option from that dropdown. Click on the Site folder from the below window as highlighted. Here is the wwwroot folder that you want to access using the Kudu advanced tool.
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"))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With