Create a file in a folder of an Azure-hosted websi

2019-07-25 00:36发布

问题:

I need to copy a file from Azure Blob Storage to the "contents" folder of my Azure hosted website, and I am struggling to make this work ! Any help would be very much appreciated. The code works fine on my local server, but fails when hosted on Azure.

Here is my function:


public bool CopyFromAzure(string myContainer, string fileName, string filePath)
    {
        // Retrieve storage account from connection string.
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
           ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString);

        // Create the blob client.
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

        // Retrieve reference to a previously created container.
        CloudBlobContainer container = blobClient.GetContainerReference(myContainer);

        // Retrieve reference to a blob named "myblob".
        CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);

        try
        {
            // Save blob contents to a file. 
            // --> here is where an error happens !! on System.IO.File.Create
            // The value of "filePath" is: F:\sitesroot\0\Content\tmp\file_2cfe0a3d-fa7a-4ab4-a665-cdebd90567d4.pdf

            using(FileStream fs= System.IO.File.Create(@filePath))
            {
                blockBlob.DownloadToStream(fs);
            }
        }
        catch (Exception e)
        {
            return false;
        }

        return true;
    }

Question: can this be linked to Security preferences in Azure or in my website configuration?

Thxs

回答1:

Problem finally solved. For some reason, write rights were not allowed on subfolders of the Azure distribution (ie: /Content/tmp). I solved the pb by simply writing my files to the root of the project.

The code that worked:

            string filePath = HttpContext.Current.Server.MapPath("~/" + fileName);
            using (FileStream fs = System.IO.File.OpenWrite(filePath))
            {
                blockBlob.DownloadToStream(fs);
            }