下载文件后如何从Azure Blob存储中删除文件

时间:2019-08-07 16:38:39

标签: c# asp.net-mvc .net-core azure-storage azure-blob-storage

我正在存储文件的Blob存储系统上工作。 现在,我能够从Blob容器中删除/取消删除文件。 我正在尝试将文件从控制器下载回浏览器并删除该文件。

这是我的下载控制器

    public ActionResult DownloadBlob(string name) {
            CloudBlobContainer container = GetCloudBlobContainer();
            var resultSegment = container.ListBlobsSegmentedAsync(name.Split('/')[0],true ,BlobListingDetails.All,null,null,null,null).Result;
            CloudBlockBlob target = (CloudBlockBlob)resultSegment.Results.FirstOrDefault(e => e.Uri.Segments.Last() == name.Split('/')[1]);
            //var directory = container.GetDirectoryReference(name.Split('/')[0]);
            //var block = directory.GetBlockBlobReference(name.Split('/')[1]);

            if (target.ExistsAsync().Result) {
            } else {
                target.UndeleteAsync().Wait();
            }

            Stream stream = target.OpenReadAsync().Result;
            string contentType = target.Properties.ContentType;
            ;

            target.DeleteIfExistsAsync();

            return new FileStreamResult(stream, contentType) {
                FileDownloadName = "Downloaded_" + name.Split('/')[1]
            };
    }

因此,如果我有一个已删除的文件,我想取消删除它,下载它,然后再次删除它。(“软删除”处于打开状态) 有没有办法做到这一点,以便在return语句后执行删除操作

1 个答案:

答案 0 :(得分:1)

您是否在当前代码中遇到错误“找不到Blob”?如是, 您可以使用MemoryStream和blob.DownloadToStream(memoryStream),然后只需在下载完成后删除blob,而无需在return语句后调用delete。

我安装了以下blob存储的nuget软件包:Microsoft.Azure.Storage.Blob, Version 11.0.0,该软件包支持异步和非异步blob方法。您可以使用此程序包,也可以根据注释将当前代码更改为异步。

示例代码在我这方面效果很好(测试代码,您可以随时进行修改以满足您的需要):

    public IActionResult Contact()
    {
        string account_name = "xx";
        string account_key = "xx";

        CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials(account_name, account_key), true);
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer blobContainer = blobClient.GetContainerReference("test1");
        CloudBlockBlob blob = blobContainer.GetBlockBlobReference("df1.JPG");

        if (!blob.Exists())
        {
            blob.Undelete();
        }

        MemoryStream memoryStream = new MemoryStream();

        blob.DownloadToStream(memoryStream);
        memoryStream.Position = 0;
        string contentType = blob.Properties.ContentType;

       blob.DeleteIfExists();

        return new FileStreamResult(memoryStream, contentType)
        {
            FileDownloadName = blob.Name
        };

    }