Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create and save a temporary file on Microsoft Azure virtual server

Tags:

c#

azure

I am using a free MS Azure virtual webserver for my site.

On my dev machine I can successfully create a CSV file, save it to a relative temp directory, and then download it to the browser client.

However, when I run it from the Azure site, I get the following error:

System.IO.DirectoryNotFoundException: Could not find a part of the path 'D:\home\site\wwwroot\temp\somefile.csv'.

Does the free version of Azure Websites block us from saving files to disk? If not, where are we allowed to create/save files that we generate on the fly?

Code Example

private FilePathResult SaveVolunteersToCsvFile(List<Volunteer> volunteers)
{
    string virtualPathToDirectory = "~/temp";
    string physicalPathToDirectory = Server.MapPath(virtualPathToDirectory);
    string fileName = "Volunteers.csv";
    string pathToFile = Path.Combine(physicalPathToDirectory, fileName);
    StringBuilder sb = new StringBuilder();

    // Column Headers
    sb.AppendLine("First Name,Last Name,Phone,Email,Approved,Has Background Check");

    // CSV Rows
    foreach (var volunteer in volunteers)
    {
        sb.AppendLine(string.Format("{0},{1},{2},{3},{4},{5},{6}",
            volunteer.FirstName, volunteer.LastName, volunteer.MobilePhone.FormatPhoneNumber(), volunteer.EmailAddress, volunteer.IsApproved, volunteer.HasBackgroundCheckOnFile));
    }

    using (StreamWriter outfile = new StreamWriter(pathToFile))
    {
        outfile.Write(sb.ToString());
    }
    return File(Server.MapPath(virtualPathToDirectory + "/" + fileName), "text/csv", fileName);
}
like image 745
Jed Avatar asked Sep 20 '25 06:09

Jed


2 Answers

Make sure that the ~/temp folder gets published to the server, as it's possible your publish process isn't including it.

like image 197
mason Avatar answered Sep 22 '25 20:09

mason


Azure Websites provide environment variables that you can use to get to things like a temporary storage folder. For example, there is a "TEMP" variable you could access to get a path to the TEMP folder specific to your Website.

Change line 2 in your method to this:

        //string physicalPathToDirectory = Server.MapPath(virtualPathToDirectory);
        string physicalPathToDirectory = Environment.GetEnvironmentVariable("TEMP");

Then change the last line to this:

        //return File(Server.MapPath(virtualPathToDirectory + "/" + fileName), "text/csv", fileName);
        return File(pathToFile, "text/csv", fileName);
like image 40
Rick Rainey Avatar answered Sep 22 '25 19:09

Rick Rainey