从 azure blob 存储下载 zip 后无法访问 zip

时间:2021-05-20 06:59:39

标签: c# azure asp.net-core

我有一个 asp.net core web api 控制器,它正在使用此代码从 azure blob 存储下载 zip 文件。

        CloudStorageAccount mycloudStorageAccount = CloudStorageAccount.Parse(storageAccount_connectionString);
        CloudBlobClient blobClient = mycloudStorageAccount.CreateCloudBlobClient();

        CloudBlobContainer container = blobClient.GetContainerReference(azure_ContainerName);
        CloudBlockBlob cloudBlockBlob = container.GetBlockBlobReference(filetoDownload);

        FileStream file = File.OpenWrite(@"D:\Downloads\"+filetoDownload);
        cloudBlockBlob.DownloadToStreamAsync(file);
        Console.WriteLine("Download completed!");

下载后,我尝试使用此代码使用另一个控制器解压缩。

        string zipPath = @"D:\Downloads\AUSAssetData_4F3CDD1E-B0B1-4FD9-9663-08B5DE0CE014_DMFPackage.zip";
        string extractPath = @"D:\Downloads\Extracted";
        ZipFile.ExtractToDirectory(zipPath, extractPath, false);

但是在尝试解压缩文件时,我收到此错误 System.IO.IOException: The process cannot access the file。我想知道有没有一种方法可以在不停止整个服务的情况下停止以前的控制器进程,以便我的解压缩控制器可以访问它。

1 个答案:

答案 0 :(得分:2)

您收到此错误的原因是您的 FileStream 对象仍处于打开状态并且锁定了文件。您将需要关闭/处置该对象。

尝试使用以下代码:

using (FileStream file = File.OpenWrite(@"D:\Downloads\"+filetoDownload))
{
    await cloudBlockBlob.DownloadToStreamAsync(file);//You will need to await this process or use DownloadToStream method.
    Console.WriteLine("Download completed!");
}
相关问题