by Steve Marx via Steve Marx's blog on 4/16/2010 5:24:00 AM
A question came up today on Stack Overflow of how to test for the existence of a blob. From the REST API, the best method seems to be Get Blob Properties, which does a HEAD request against the blob. That will return a 404 if the blob doesn’t exist, and if the blob does exist, it only returns the headers that would typically come with the blob contents. This makes it an efficient way to test for the existence of a blob.
HEAD
404
From the .NET StorageClient library, the method which maps to Get Blob Properties is CloudBlob.FetchAttributes(). The following extension method implements an Exists() method on CloudBlob:
CloudBlob.FetchAttributes()
Exists()
CloudBlob
public static class BlobExtensions { public static bool Exists(this CloudBlob blob) { try { blob.FetchAttributes(); return true; } catch (StorageClientException e) { if (e.ErrorCode == StorageErrorCode.ResourceNotFound) { return false; } else { throw; } } } }
Using this extension method, we can test for the existence of a particular blob in a natural way. Here’s a little program that tells you whether a particular blob exists:
static void Main(string[] args) { var blob = CloudStorageAccount.DevelopmentStorageAccount .CreateCloudBlobClient().GetBlobReference(args[0]); // or CloudStorageAccount.Parse("<your connection string>") if (blob.Exists()) { Console.WriteLine("The blob exists!"); } else { Console.WriteLine("The blob doesn't exist."); } }
Note that the above extension method has a side-effect, in that it fills in the CloudBlob.Attributes property. This is probably fine (and an optimization if you’re later going to read those attributes), but I thought I’d point it out.
CloudBlob.Attributes
[UPDATE 4/19/2010] This same technique works great with containers also. Here’s a similar extension method on CloudBlobContainer:
CloudBlobContainer
public static class ContainerExtensions { public static bool Exists(this CloudBlobContainer container) { try { container.FetchAttributes(); return true; } catch (StorageClientException e) { if (e.ErrorCode == StorageErrorCode.ResourceNotFound) { return false; } else { throw; } } } }
Original Post: Testing Existence of a Windows Azure Blob
The content of the postings is owned by the respective author. AzureFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on AzureFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.