save file to temporary location in Azure Functions

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!!


Solution 1:

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

Solution 2:

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);  
}