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.