【问题标题】:How to delete files from blob container?如何从 blob 容器中删除文件?
【发布时间】:2016-07-29 14:05:43
【问题描述】:
private readonly CloudBlobContainer _blobContainer;

public void Remove()
{
    if (_blobContainer.Exists())
    {
       _blobContainer.Delete();
    }
}

如何不删除整个容器,而是删除容器中的一些List<string> disks

【问题讨论】:

  • @h.o.m.a.n 他希望能够删除特定的 blob,但不是全部......
  • @CallumLinington 您可以修改此代码以从容器中删除一些文件,例如 'Parallel.ForEach(_cloudBlobClient.GetContainerReference(nameContainer).ListBlobs(), x => { if (list.Contains(( (CloudBlob)x).Name)) ((CloudBlob)x).DeleteIfExists(); });'

标签: c# azure


【解决方案1】:

这是我使用的代码:

private CloudBlobContainer blobContainer;

public void DeleteFile(string uniqueFileIdentifier)
{
    this.AssertBlobContainer();

    var blob = this.blobContainer.GetBlockBlobReference(uniqueFileIdentifier);
    blob.DeleteIfExists();
}

private void AssertBlobContainer()
{
    // only do once
    if (this.blobContainer == null)
    {
        lock (this.blobContainerLockObj)
        {
            if (this.blobContainer == null)
            {
                var client = this.cloudStorageAccount.CreateCloudBlobClient();

                this.blobContainer = client.GetContainerReference(this.containerName.ToLowerInvariant());

                if (!this.blobContainer.Exists())
                {
                    throw new CustomRuntimeException("Container {0} does not exist in azure account", containerName);
                }
            }
        }
    }

    if (this.blobContainer == null) throw new NullReferenceException("Blob Empty");
}

如果您知道不会同时访问锁定代码,则可以忽略锁定代码

显然,您已经对 blobContainer 进行了排序,所以您只需要没有 this.AssertBlobContainer()DeleteFile 方法。

【讨论】:

  • var blob = this.blobContainer.GetBlockBlobReference(fileName); 中的文件名是什么?我猜它的 uniqueFileIdentifier。
  • 好东西,我建议不要在每次调用之前调用 Assert,而是通过使用带有支持字段的属性来利用单例模式
  • 考虑到这样你不会删除它的快照,只是删除 blob 本身
  • 你能更新这个答案吗? CloudBlobContainerMicrosoft.Azure.Storage 此后已被弃用。
  • 是的,下周我会做的-谢谢你提醒我
【解决方案2】:

记住SDK v11 has been deprecated,加上SDK v12

using Azure.Storage.Blobs;
...
BlobServiceClient blobServiceClient = new BlobServiceClient("StorageConnectionString");
BlobContainerClient cont = blobServiceClient.GetBlobContainerClient("containerName");
cont.GetBlobClient("FileName.ext").DeleteIfExists();

【讨论】:

【解决方案3】:

有一个名为 DeleteIfExistis() 的方法。返回真/假。

CloudBlockBlob blob = CloudBlobContainer.GetBlockBlobReference(fileName);
blob.DeleteIfExists();

Filename 是 ContainerName/FileName,如果在文件夹中,您也需要提及该文件夹。像 ContainerName/AppData/FileName 一样,并且会起作用。

【讨论】:

    【解决方案4】:

    执行删除的单行代码

    private static async Task DeleteBLOBFile(string blobNamewithFileExtension)
            {
                BlobClient blobClient = new BlobClient(blobConnectionString,containerName,blobNamewithFileExtension);
                await blobClient.DeleteIfExistsAsync();            
            }
    

    【讨论】:

      【解决方案5】:

      我们可以使用cloudBlobContainer.ListBlobsSegmentedAsync 列出blob,然后将其转换为ICloudBlob,以便您可以执行DeleteIfExistsAsync。下面是工作示例函数。希望对您有所帮助。

      public async Task < bool > PerformTasks() {
          try {
              if (CloudStorageAccount.TryParse(StorageConnectionString, out CloudStorageAccount cloudStorageAccount)) {
                  var cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
                  var cloudBlobContainer = cloudBlobClient.GetContainerReference(_blobContainerName);
                  if (await cloudBlobContainer.ExistsAsync()) {
                      BlobContinuationToken blobContinuationToken = null;
                      var blobList = await cloudBlobContainer.ListBlobsSegmentedAsync(blobContinuationToken);
                      var cloudBlobList = blobList.Results.Select(blb = >blb as ICloudBlob);
                      foreach(var item in cloudBlobList) {
                          await item.DeleteIfExistsAsync();
                      }
                      return true;
                  }
                  else {
                      _logger.LogError(ErrorMessages.NoBlobContainerAvailable);
                  }
              }
              else {
                  _logger.LogError(ErrorMessages.NoStorageConnectionStringAvailable);
              }
          }
          catch(Exception ex) {
              _logger.LogError(ex.Message);
          }
          return false;
      }
      

      【讨论】:

        【解决方案6】:
        List<string> FileNameList = new List<string>();
        FileNameList = fileName.Split(',').Where(t => t.ToString().Trim() != "").ToList();
        CloudBlobClient client;
        CloudBlobContainer container;
        CloudBlockBlob blob;
        string accessKey;
        string accountName;
        string connectionString;
        accessKey = Environment.GetEnvironmentVariable("StorageAccountaccessKey");
        accountName = Environment.GetEnvironmentVariable("StorageAccountName");
        connectionString = Environment.GetEnvironmentVariable("StorageAccountConnectionString");
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        client = storageAccount.CreateCloudBlobClient();
        string containerName = tenantId;
        container = client.GetContainerReference(containerName);
        
        foreach(var file in FileNameList)
        {
           blob = container.GetBlockBlobReference(file);
           blob.DeleteIfExists();
        }
        

        【讨论】:

        • 此代码有效,但一团糟。未使用的变量、错误的命名等。如果要提交给其他人,请清理干净。
        猜你喜欢
        • 2019-04-13
        • 2016-04-16
        • 2020-05-10
        • 2020-01-01
        • 2020-04-09
        • 2021-10-09
        • 2020-01-02
        • 2019-02-08
        • 1970-01-01
        相关资源
        最近更新 更多