Reputation: 1277
I have an Azure function and I am trying to save a .xlsx file to a temporary folder. My code works locally, but when I publish to Azure I get an error message.
string projectDirectory = Directory.GetParent(Environment.CurrentDirectory).Parent.Parent.FullName + @"\temp\";
string tempFilename = "abc.xlsx";
string pathTradeRecFile = Path.Combine(projectDirectory, tempFilename);
My error message. <--- Access to the path 'C:\Program Files (x86)\SiteExtensions\temp\abc.xlsx' is denied.
Can someone please tell me how I can save this file somewhere? I made a folder in my structure named "temp" as one possible solution, but I can't seem to access it.
Any help would be greatly appreciated!!
Upvotes: 8
Views: 15763
Reputation: 797
In case of Python runtime, base OS is going to be Linux so you can work it out something like below:
import tempfile
# Get the temporary file
# With suffix/prefix you can add suffix/prefix
# delete=False prevents this file from deletion as soon as you close it
temp_file = tempfile.NamedTemporaryFile(suffix=".tf.json", delete=False)
# File Name with full path
print(temp_file.name)
Upvotes: 0
Reputation: 1
Environment variables as seen by an Azure Function aren't the same as the overall OS Environment variables. See this page for how to configure them: https://learn.microsoft.com/en-us/azure/azure-functions/functions-how-to-use-azure-function-app-settings?tabs=portal#settings. The System.Environment.GetEnvironmentVariable(name) call returns this value when running in Azure. Locally, the value comes from the local.settings.json file: https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-class-library?tabs=v2%2Ccmd#environment-variables.
Upvotes: 0
Reputation: 16208
Please do not use something like Environment.CurrentDirectory
in Azure Functions (or actually, just anywhere) to get a temp folder. Instead use the .NET-native method to do so:
Path.GetTempPath()
So ideally use something like this:
string pathTradeRecFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".xlsx");
Upvotes: 14
Reputation: 10849
My apologies, but I did not get your intention to save file in Azure storage file system? However if azure function allows to save file locally then you should use Directory.GetCurrentDirectory();
which resolves to D:\home\site\wwwroot
path.
Coming to my initial point, if you have a requirement to save the file locally to finally upload at persistent storage like Azure Blob
then you don't need to save file locally at file system; you can use MemoryStream
as shown in below code to upload the content at Azure blob
using (var ms = new MemoryStream())
{
using (StreamWriter writer = new StreamWriter(ms))
{
writer.Write(obj); // here obj represents the file data which you need to upload
writer.Flush();
ms.Position = 0
};
await blob.UploadFromStreamAsync(ms);
}
Upvotes: 1