Checking if a blob exists in Azure Storage

I've got a very simple question (I hope!) - I just want to find out if a blob (with a name I've defined) exists in a particular container. I'll be downloading it if it does exist, and if it doesn't then I'll do something else.

I've done some searching on the intertubes and apparently there used to be a function called DoesExist or something similar... but as with so many of the Azure APIs, this no longer seems to be there (or if it is, has a very cleverly disguised name).


The new API has the .Exists() function call. Just make sure that you use the GetBlockBlobReference , which doesn't perform the call to the server. It makes the function as easy as:

public static bool BlobExistsOnCloud(CloudBlobClient client, 
    string containerName, string key)
{
     return client.GetContainerReference(containerName)
                  .GetBlockBlobReference(key)
                  .Exists();  
}

Note: This answer is out of date now. Please see Richard's answer for an easy way to check for existence

No, you're not missing something simple... we did a good job of hiding this method in the new StorageClient library. :)

I just wrote a blog post to answer your question: http://blog.smarx.com/posts/testing-existence-of-a-windows-azure-blob.

The short answer is: use CloudBlob.FetchAttributes(), which does a HEAD request against the blob.


似乎跛脚你需要捕捉一个异常来测试它是否存在。

public static bool Exists(this CloudBlob blob)
{
    try
    {
        blob.FetchAttributes();
        return true;
    }
    catch (StorageClientException e)
    {
        if (e.ErrorCode == StorageErrorCode.ResourceNotFound)
        {
            return false;
        }
        else
        {
            throw;
        }
    }
}
链接地址: http://www.djcxy.com/p/66100.html

上一篇: 在Blob存储中清理/管理Azure日志文件/失败的请求日志

下一篇: 检查Azure存储中是否存在Blob