web-dev-qa-db-fra.com

Comment obtenir une liste de tous les objets blob dans un conteneur dans Azure?

J'ai le nom et la clé de compte d'un compte de stockage dans Azure. J'ai besoin d'obtenir une liste de tous les blobs dans un conteneur de ce compte. (Le conteneur "$ logs").

Je peux obtenir les informations d'un blob spécifique en utilisant la classe CloudBlobClient mais je ne peux pas comprendre comment obtenir une liste de tous les blobs dans le conteneur $ logs.

13
SKLAK

Il existe un exemple de la liste de tous les objets blob dans un conteneur à https://Azure.Microsoft.com/en-us/documentation/articles/storage-dotnet-how-to-use-blobs/ # list-the-blobs-in-a-container :

// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference("photos");

// Loop over items within the container and output the length and URI.
foreach (IListBlobItem item in container.ListBlobs(null, false))
{
    if (item.GetType() == typeof(CloudBlockBlob))
    {
        CloudBlockBlob blob = (CloudBlockBlob)item;
        Console.WriteLine("Block blob of length {0}: {1}", blob.Properties.Length, blob.Uri);
    }
    else if (item.GetType() == typeof(CloudPageBlob))
    {
        CloudPageBlob pageBlob = (CloudPageBlob)item;
        Console.WriteLine("Page blob of length {0}: {1}", pageBlob.Properties.Length, pageBlob.Uri);
    }
    else if (item.GetType() == typeof(CloudBlobDirectory))
    {
        CloudBlobDirectory directory = (CloudBlobDirectory)item;
        Console.WriteLine("Directory: {0}", directory.Uri);
    }
}
15

Étant donné que le nom de votre conteneur est $ logs, je pense que votre type d'objet blob est ajouter un objet blob. Voici une méthode pour obtenir tous les blobs et renvoyer IEnumerable:

    private static CloudBlobClient _blobClient = CloudStorageAccount.Parse("connectionstring").CreateCloudBlobClient();
    public IEnumerable<CloudAppendBlob> GetBlobs()
    {
        var container = _blobClient.GetContainerReference("$logs");
        BlobContinuationToken continuationToken = null;

        do
        {
            var response = container.ListBlobsSegmented(string.Empty, true, BlobListingDetails.None, new int?(), continuationToken, null, null);
            continuationToken = response.ContinuationToken;
            foreach (var blob in response.Results.OfType<CloudAppendBlob>())
            {
                yield return blob;
            }
        } while (continuationToken != null);
    }

La méthode peut être asynchrone, utilisez simplement ListBlobsSegmentedAsync. Une chose que vous devez noter est que l'argument useFlatBlobListing doit être vrai, ce qui signifie que ListBlobs renverra une liste plate de fichiers par opposition à une liste hiérarchique.

6
Feiyu Zhou

Voici l'appel d'API mis à jour pour WindowsAzure.Storage v9.0:

private static CloudBlobClient _blobClient = CloudStorageAccount.Parse("connectionstring").CreateCloudBlobClient();

public async Task<IEnumerable<CloudAppendBlob>> GetBlobs()
{
    var container = _blobClient.GetContainerReference("$logs");
    BlobContinuationToken continuationToken = null;

    //Use maxResultsPerQuery to limit the number of results per query as desired. `null` will have the query return the entire contents of the blob container
    int? maxResultsPerQuery = null;

    do
    {
        var response = await container.ListBlobsSegmentedAsync(string.Empty, true, BlobListingDetails.None, maxResultsPerQuery, continuationToken, null, null);
        continuationToken = response.ContinuationToken;

        foreach (var blob in response.Results.OfType<CloudAppendBlob>())
        {
            yield return blob;
        }
    } while (continuationToken != null);
}

Mise à jour pour IAsyncEnumerable

IAsyncEnumerable est désormais disponible dans .NET Standard 2.1 et .NET Core 3.0

private static CloudBlobClient _blobClient = CloudStorageAccount.Parse("connectionstring").CreateCloudBlobClient();

public async IAsyncEnumerable<CloudAppendBlob> GetBlobs()
{
    var container = _blobClient.GetContainerReference("$logs");
    BlobContinuationToken continuationToken = null;

    //Use maxResultsPerQuery to limit the number of results per query as desired. `null` will have the query return the entire contents of the blob container
    int? maxResultsPerQuery = null;

    do
    {
        var response = await container.ListBlobsSegmentedAsync(string.Empty, true, BlobListingDetails.None, maxResultsPerQuery, continuationToken, null, null);
        continuationToken = response.ContinuationToken;

        foreach (var blob in response.Results.OfType<CloudAppendBlob>())
        {
            yield return blob;
        }
    } while (continuationToken != null);
}
5
Brandon Minnick

Utilisez ListBlobsSegmentedAsync qui renvoie un segment de l'ensemble de résultats total et un jeton de continuation.

réf: https://docs.Microsoft.com/en-us/Azure/storage/blobs/storage-quickstart-blobs-dotnet?tabs=windows

3
Shawn Teng

Utilisation du nouveau package Azure.Storage.Blobs

BlobServiceClient blobServiceClient = new BlobServiceClient("YourStorageConnectionString");
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient("YourContainerName");
var blobs = containerClient.GetBlobs();

foreach (var item in blobs){
    Console.WriteLine(item.Name);
}
1
rc125