C# retrieving a list of blobs from Azure

后端 未结 2 2063
你的背包
你的背包 2021-01-07 05:54

I need to have some archive cleanup code to remove old Azure logs after a certain retention period has occurred.

I am aware that I can do this:

Cloud         


        
2条回答
  •  攒了一身酷
    2021-01-07 06:38

    Try this pattern. Can be handy when browsing big storages. I found it much more GC and memory footprint friendly

    var blobAccount = "";
    var apiKey = "";
    var containerName = "";
    var storageCredentials = new StorageCredentials(blobAccount, apiKey);
    
    var account = new CloudStorageAccount(storageCredentials, true);
    var blobClient = account.CreateCloudBlobClient();
    var container = blobClient.GetContainerReference(containerName);
    var blobLimit = 500
    
    if (container == null) { return; }
    
    var blobContinuationToken = new BlobContinuationToken();
    
    using (var fs = new FileStream("Output.csv", FileMode.Create))
    {
        var sw = new StreamWriter(fs);
        sw.WriteLine("Type,Name,Length");
    
        BlobContinuationToken continuationToken = null;
        do
        {   
            var blobList = container.ListBlobsSegmented("",
                                       true,
                                       BlobListingDetails.Metadata,
                                       blobLimit,
                                       continuationToken,
                                       new BlobRequestOptions
                                       {
                                           LocationMode = LocationMode.PrimaryOnly
                                       },
                                       null);
    
            continuationToken = blobList.ContinuationToken;
    
            // I was looking only for BlockBlobs
            foreach (var item in blobList.Results.OfType())
            {
                sw.WriteLine($"block,\"{item.Name}\",{item.Properties.Length}");
            }
    
        } while (continuationToken != null);
    }
    

提交回复
热议问题