Azure: Checking if a blob exists using its URI

Having only a storage account (CloudBlobClient) and a blob URI makes it a little bit tricky to check if the blob actually exists. To be able to use the ​​ICloudBlob.Exists()​ method, you have to have a blob-reference and there is no easy way to get it from URI.

If you just need to know if the blob exists, you can make a simple HTTP HEAD request to the URI with any HTTP client.

If you need the blob-reference for further use, there is a CloudBlobClient.GetBlobReferenceFromServer(Uri blobUri) method. As you call it, it hits the server with a HEAD request and throws an exception if the blob does not exist (so there is no chance to use the Exists method later).

You can catch this exception with a nice pattern-matching:

ICloudBlob blob;
try
{
    blob = blobClient.GetBlobReferenceFromServer(new Uri(url));
}
catch (Microsoft.WindowsAzure.Storage.StorageException ex)
            when ((ex.InnerException is System.Net.WebException wex)
                    && (wex.Response is System.Net.HttpWebResponse httpWebResponse)
                    && (httpWebResponse.StatusCode == System.Net.HttpStatusCode.NotFound))
{
    // blob does not exist, do whatever you need here
    return null;
}
// further code able to use the blob-reference

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s