Does a Blob Exist?
One of the most common task relating to blobs is a simple check to verify if it exist. Unfortunately there is no method or property for CloudBlob that provides an answer.
I wrote a simple extension method to do that:
public static bool Exists(this CloudBlob blob)
{
try
{
blob.FetchAttributes();
return true;
}
catch (StorageClientException e)
{
if (e.ErrorCode == StorageErrorCode.ResourceNotFound)
{
return false;
}
throw;
}
}
but when I run the method I got sometimes an InvalidOperationException "BlobType of the blob reference doesn't match BlobType of the blob". No one can explain this including Steve Marx but many developers have seen this happens. So I changed my code to:
public static bool Exists(this CloudBlob blob)
{
try
{
if (blob is CloudBlockBlob)
{
((CloudBlockBlob)blob).FetchAttributes();
return true;
}
if (blob is CloudPageBlob)
{
((CloudPageBlob)blob).FetchAttributes();
return true;
}
try
{
(blob).FetchAttributes();
return true;
}
catch (InvalidOperationException ex)
{
if (ex.Message == "BlobType of the blob reference doesn't match BlobType of the blob")
return true;
throw;
}
}
catch (StorageClientException e)
{
if (e.ErrorCode == StorageErrorCode.ResourceNotFound)
{
return false;
}
throw;
}
}
Enjoy
Manu