views:

549

answers:

4

Hi, I've got a very simple question (I hope!) - I just want to find out if a blob (with a name I've defined) exists in a particular container. I'll be downloading it if it does exist, and if it doesn't then I'll do something else.

I've done some searching on the intertubes and apparently there used to be a function called DoesExist or something similar... but as with so many of the Azure APIs, this no longer seems to be there (or if it is, has a very cleverly disguised name).

Or maybe I'm missing something simple... :)

John

+3  A: 

No, you're not missing something simple... we did a good job of hiding this method in the new StorageClient library. :)

I just wrote a blog post to answer your question: http://blog.smarx.com/posts/testing-existence-of-a-windows-azure-blob.

The short answer is: use CloudBlob.FetchAttributes(), which does a HEAD request against the blob.

smarx
FetchAttributes() takes a long time to run (in development storage at least) if the file hasn't been fully committed yet, i.e. just consists of uncommitted blocks.
tjrobinson
If you are going to fetch the blob anyway like the OP intends to do, why not try and download the content right away? If it's not there it will throw just like FetchAttributes. Doing this check first is just an extra request, or am I missing something?
Marnix van Valen
Marnix makes an excellent point. If you're going to download it anyway, just try to download it.
smarx
+1  A: 

If the blob is public you can, of course, just send an HTTP HEAD request -- from any of the zillions of languages/environments/platforms that know how do that -- and check the response.

The core Azure APIs are RESTful XML-based HTTP interfaces. The StorageClient library is one of many possible wrappers around them. Here's another that Sriram Krishnan did in Python:

http://www.sriramkrishnan.com/blog/2008/11/python-wrapper-for-windows-azure.html

It also shows how to authenticate at the HTTP level.

I've done a similar thing for myself in C#, because I prefer to see Azure through the lens of HTTP/REST rather than through the lens of the StorageClient library. For quite a while I hadn't even bothered to implement an ExistsBlob method. All my blobs were public, and it was trivial to do HTTP HEAD.

judell
A: 

Seem lame that you need to catch an exception to test it the blob exists.

public static bool Exists(this CloudBlob blob)
{
    try
    {
        blob.FetchAttributes();
        return true;
    }
    catch (StorageClientException e)
    {
        if (e.ErrorCode == StorageErrorCode.ResourceNotFound)
        {
            return false;
        }
        else
        {
            throw;
        }
    }
}
nathanw
A: 

Yea, in my opinion, this is not a pretty solutioin.

There should be a methode like this: bool blobExists = _cloudBlobContainer.Exists("blobname");

cheers manuel

manuel