如何从blob容器中删除文件?

15 c# azure

private readonly CloudBlobContainer _blobContainer;

public void Remove()
{
    if (_blobContainer.Exists())
    {
       _blobContainer.Delete();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Cal*_*ton 25

这是我使用的代码:

private CloudBlobContainer blobContainer;

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

    var blob = this.blobContainer.GetBlockBlobReference(fileName);
    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");
}
Run Code Online (Sandbox Code Playgroud)

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

显然,你已经对blobContainer这些东西进行了排序,所以你需要的只是DeleteFile没有的东西this.AssertBlobContainer().

  • var blob = this.blobContainer.GetBlockBlobReference(fileName);中的文件名是什么?我猜想它的uniqueFileIdentifier。 (2认同)

小智 9

记住SDK v11 已被弃用,使用SDK v12

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