Monday, August 2, 2010

How to check if a BlobContainer or a Blob exists

Earlier versions of the Windows Azure SDK provided two methods DoesContainerExist() and DoesBlobExist() to determine whether a given BlobContainer or Blob already exists. In the current release of the SDK those methods have been omitted, because they seduced developers to write inefficient code.

Using DoesContainerExist() and DoesBlobExist() meant more roundtrips to the storage server as necessary. In order to check the existence of Blobs or Containers it’s recommended now to check if its attributes can be retrieved. If the Blob or Container does not exist, this operation fails and throws an exception. To implement this, use the following code which needs only one roundtrip to the server (though it’s not a great style…):

var container = blobClient.GetContainerReference(path);
    // the container exists if no exception is thrown 

catch (StorageClientException ex)
    // the container does not exist

The same works for Blobs.


  1. See also my blog post on the subject:

    As I do there, it's probably better to check for the specific exception that you expect if the blob/container doesn't exist. (The code above would also silently catch other errors, like authentication failures.)

  2. container.CreateIfNotExists();

    CreateIfNotExists() method will manage both things, so we don' t need any try catch blocks

    1. Thank you for your reply. This blog post relates to an earlier SDK version where that logic was not implemented yet.