Lat*_*nis 10 c# azure blobstorage azure-storage azure-blob-storage
我没有在网上看到任何关于如何获取位于BlobContainerClient.
以前,我使用过这些Microsoft.Azure.Storage软件包,但后来它们已被弃用。我扫描目录中所有 blob 的旧代码是:
public async Task<void> ListAllBlobs(string path)
{
var myContainer = await GetCloudBlobClientAsync();
var directory = myContainer.GetDirectoryReference(path);
var blobs = await directory.ListBlobsSegmentedAsync(true, BlobListingDetails.None,
blobSettings.MaxResult, null, null, null);
var results = blobs.Results;
foreach(CloudBlockBlob b in results)
{
// non-relevant code
}
}
private async Task<CloudBlobContainer> GetCloudBlobClientAsync()
{
var storageAccount = CloudStorageAccount.Parse(azureBlobStorageConnectionString);
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference(blobStorageSettings.ContainerName);
if (!await container.ExistsAsync())
{
await container.CreateAsync();
}
return container;
}
Run Code Online (Sandbox Code Playgroud)
本质上,我将上面的代码从Microsoft.Azure.Storageover移至Azure.Storage.Blobs.
如果我要重新创建ListAllBlobs(string path)要使用的函数Azure.Storage.Blobs,我会对如何设置容器然后根据传入的路径访问内部容器 - 然后循环访问该容器中存在的 blob 感到困惑。有人可以帮忙吗?
这是我到目前为止所拥有的:
public async Task<void> ListAllBlobs(string path)
{
var myContainer = await GetCloudBlobClientAsync();
var directory = myContainer.GetBlobClient(path);
// This doesn't work because I can't do 'GetBlobs' on the Client, only on the container.
foreach(BlobItem blob in directory.GetBlobs(Blobtraits.None, BlobStates.None, string.Empty))
{
// more non-relevant code
}
}
Run Code Online (Sandbox Code Playgroud)
澄清一下,在上面的代码中,它不喜欢我GetBlobs在客户端上调用,而不是在容器上调用,但我无法传递容器的路径。
尝试这个 ...
static async Task GetBlobs()
{
string connectionString = "<connection_string>";
string containerName = "<container_name>";
var blobContainerClient = new BlobContainerClient(connectionString, containerName);
var blobs = blobContainerClient.GetBlobs(Azure.Storage.Blobs.Models.BlobTraits.All, Azure.Storage.Blobs.Models.BlobStates.All,
"YourPrefix");
foreach (var blob in blobs)
{
Console.WriteLine(blob.Name);
}
}
Run Code Online (Sandbox Code Playgroud)
...这对我有用。
你就快到了。您仍然可以使用BlobContainerClient并调用GetBlobsAsync该方法。您错过的是您需要将prefix参数的值设置为path.
所以你的代码会是这样的:
var myContainer = await GetCloudBlobClientAsync();
var blobsListingResult = await myContainer.GetBlobsAsync(prefix=path);
Run Code Online (Sandbox Code Playgroud)
更新
请尝试以下代码:
var myContainer = await GetCloudBlobClientAsync();
await foreach (BlobItem blob in myContainer.GetBlobsAsync(BlobTraits.None, BlobStates.None, path))
{
names.Add(blob.Name);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12782 次 |
| 最近记录: |