gpt4 book ai didi

c# - 下载文件后如何从 azure blob 存储中删除文件

转载 作者:行者123 更新时间:2023-12-02 23:42:51 25 4
gpt4 key购买 nike

我正在开发一个存储我的文件的 blob 存储系统。现在,我可以从 Blob 容器中删除/取消删除文件。我正在尝试将文件从 Controller 下载回浏览器并删除该文件。

这是我的下载 Controller

    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 语句之后执行

最佳答案

您当前的代码中是否遇到“找不到 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
};

}

关于c# - 下载文件后如何从 azure blob 存储中删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57398904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com