如何在 Azure Blob Storage V12 中检查容器是否存在

24

在使用Azure Blob Storage SDK V11时,如果您想要创建一个容器但不确定该容器是否存在,可以使用CreateIfNotExists。

然而,在V12版本中,CreateIfNotExists已不再可用,我能从微软找到的唯一示例是仅创建Container而不检查它是否已经存在。

那么,有人知道在V12中在尝试创建容器之前检查容器是否存在的最佳做法吗?

顺便说一下,我正在开发ASP.Net Core 3.1。

4个回答

45
在v12中,有两种方法可以检查容器是否存在。 1.
BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);

//get a BlobContainerClient
var container = blobServiceClient.GetBlobContainerClient("the container name");
            
//you can check if the container exists or not, then determine to create it or not
bool isExist = container.Exists();
if (!isExist)
{
    container.Create();
}

//or you can directly use this method to create a container if it does not exist.
 container.CreateIfNotExists();

您可以直接创建一个BlobContainerClient,然后使用以下代码:

//create a BlobContainerClient 
BlobContainerClient blobContainer = new BlobContainerClient("storage connection string", "the container name");
    
//use code below to check if the container exists, then determine to create it or not
bool isExists = blobContainer.Exists();
if (!isExist)
{
   blobContainer .Create();
}
    
//or use this code to create the container directly, if it does not exist.
blobContainer.CreateIfNotExists();

1
@Phil,你使用的是哪个包和版本?最好提供一些示例代码 :) - Ivan Glasenberg
1
我部分有责任,我正在使用 new BlobContainerClient(new Uri("..")) 的Uri重载。我没有传递TokenCredential,例如 new DefaultAzureCredential()。错误可能会更有帮助,并提示授权问题而不是404。 - Phil
@IvanYang 你知道使用 SAS 而不是连接字符串是否有任何限制吗?当使用连接字符串时,它可以完美地工作,但当我使用 SAS 令牌时,它会抛出一个异常,说该 blob 不存在,但检查的是一个容器,所以我不明白这个错误。 - gab
1
@IvanYang,我已经发布了问题和代码。谢谢! - gab
我似乎漏掉了什么:对于我来说,bool isExist = container.Exists(); 无法编译,因为 Exists() 现在不返回 bool,而是返回 Response<bool> - O. R. Mapper
显示剩余3条评论

7

接受的答案是可以的。但我通常使用其异步版本。

var _blobServiceClient = new BlobServiceClient(YOURCONNECTIONSTRING);
var containerClient = _blobServiceClient.GetBlobContainerClient(YOURCONTAINERNAME);
await containerClient.CreateIfNotExistsAsync(Azure.Storage.Blobs.Models.PublicAccessType.BlobContainer);

我使用的版本是Azure.Storage.Blobs v12.4.1。

2
然而在V12版本中,CreateIfNotExists已不再提供,我能找到的唯一示例是仅仅创建一个容器而不检查它是否已经存在。
我不确定你为什么说“存储客户端库的12版中不再提供CreateIfNotExists”。在BlobContainerClient类中肯定有这个函数。以下是直接链接:CreateIfNotExists。
    var connectionString = "UseDevelopmentStorage=true";            
    var containerClient = new BlobContainerClient(connectionString, containerName);
    containerClient.CreateIfNotExists();

1
谢谢你的链接Gaurav,这很有帮助。我只是找不到使用CreateIfNotExists的V12代码示例,并且在某个地方读到它已不再可用。 - Mitch

-1
我有以下方法来获取SAS令牌,一切都正常运行。
private Uri GetUriSasToken()
    {
        string storedPolicyName = null;
        string connectionString = _config.GetConnectionString("BlobConnection");
        BlobContainerClient containerClient = new BlobContainerClient(connectionString, "stock");

        // Check whether this BlobContainerClient object has been authorized with Shared Key.
        if (containerClient.CanGenerateSasUri)
        {
            // Create a SAS token that's valid for one hour.
            BlobSasBuilder sasBuilder = new BlobSasBuilder()
            {
                BlobContainerName = containerClient.Name,
                Resource = "c"
            };

            if (storedPolicyName == null)
            {
                sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddHours(1);
                sasBuilder.SetPermissions(BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List);
            }
            else
            {
                sasBuilder.Identifier = storedPolicyName;
            }

            Uri sasUri = containerClient.GenerateSasUri(sasBuilder);
            return sasUri;
        }
        else
        {
            _logger.LogError(@"BlobContainerClient must be authorized with Shared Key credentials to create a service SAS.");
            return null;
        }
                 
    }

接下来,我使用以下代码调用上述方法:

   BlobServiceClient blobServiceClient = new BlobServiceClient(GetUriSasToken(), null);
        var blobName = _config.GetValue<string>("BlobName");
        var containerName = _config.GetValue<string>("ContainerName");            
        var fileName = _config.GetValue<string>("FileName");            
        var containerClient = blobServiceClient.GetBlobContainerClient(containerName);

有没有办法可以验证容器是否存在?

我不确定我能做什么:

containerClient.Exists

我使用它,但返回一个错误,指出 Blob 不存在,但我想先检查容器是否存在。

有人做过这个吗?


我看到在GetUriSasToken()方法中,您指定了一个名为“stock”的容器名称来生成sas_token。那么这个sas_token只能用于该容器“stock”。最好创建一个账户级别的sas_token :)。 - Ivan Glasenberg
@IvanYang 已经明白了,感谢您的澄清。您知道如何创建此帐户级令牌吗?我在文档中看到了这个页面 https://learn.microsoft.com/en-us/rest/api/storageservices/create-service-sas 但是我不清楚如何指定帐户级别的范围。 - gab
1
请问您能否在StackOverflow上添加一个新问题,然后将问题链接发给我?请注意,您添加的是答案而不是问题。 - Ivan Glasenberg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接