[英]In Azure Blob container, How to delete all files by name under a directory?
I use Azure blob client API, and I want to delete all files name "fieldA".我使用 Azure blob 客户端 API,我想删除所有文件名为“fieldA”。 My diretory is as
我的目录是
/all/folder1/fieldA
/all/folder1/fieldB
/all/folder2/fieldA
/all/folder2/fieldC
After delete, I want it become删除后,我希望它成为
/all/folder1/fieldB
/all/folder2/fieldC
I do some search it says Azure blob container does not support regular expression search.我做了一些搜索,它说 Azure blob 容器不支持正则表达式搜索。 So I think the only way is to
list all blob
-> filter fieldA
-> delete
.所以我认为唯一的方法是
list all blob
-> filter fieldA
-> delete
。
I wrote some code as following, and it keep give me unknow error.我写了一些代码如下,它一直给我未知的错误。 Could I know if there is sth not right?
我能知道有什么不对吗?
var ctoken = new BlobContinuationToken();
do
{
var result = await blobContainer.ListBlobsSegmentedAsync('/all', true, BlobListingDetails.None, null, ctoken, null, null);
ctoken = result.ContinuationToken;
var a = result.Results.Where(item => (item as CloudBlob).Name.EndsWith("fieldA"));
await Task.WhenAll(a
.Select(item => (item as CloudBlob)?.DeleteAsync())
.Where(task => task != null)
);
} while (ctoken != null);
If you want to delete all files by name under a directory, please refer to the following code如果要按名称删除某个目录下的所有文件,请参考以下代码
My container is as below我的容器如下
container: test
blob :
/all/folder1/test.txt
/all/folder1/test1.txt
/all/folder2/test.txt
/all/folder2/test2.txt
Code代码
static async Task Main(string[] args)
{
string accountName = "andyprivate";
string keyValue = "";
string containerName = "test";
StorageCredentials credentials = new StorageCredentials(accountName, keyValue);
CloudBlobContainer container = new CloudBlobContainer(new Uri($"https://{accountName}.blob.core.windows.net/{containerName}"), credentials);
string prefix = "all/";
await ListBlobsHierarchicalListingAsync(container, prefix);
}
private static async Task ListBlobsHierarchicalListingAsync(CloudBlobContainer container, string prefix)
{
BlobContinuationToken continuationToken = null;
do
{
BlobResultSegment resultSegment = await container.ListBlobsSegmentedAsync(prefix,
false, BlobListingDetails.Metadata, null, continuationToken, null, null);
var a = resultSegment.Results.OfType<CloudBlob>().Where(item => item.Name.EndsWith("test.txt")).ToList();
var b = resultSegment.Results.OfType<CloudBlobDirectory>().ToList();
await Task.WhenAll(a
.Select(item => item?.DeleteAsync())
.Where(task => task != null));
foreach (var r1 in b) {
Console.WriteLine("Virtual directory prefix: {0}", r1.Prefix);
await ListBlobsHierarchicalListingAsync(container, r1.Prefix);
}
continuationToken = resultSegment.ContinuationToken;
} while (continuationToken != null);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.