Tue, 20 Apr 2010

Put Blob Without Overwrite

A question came up recently of how to store a Windows Azure blob without overwriting the blob if it already exists. This quick post will show you how to do this using the .NET StorageClient library.

To figure out how to do this, I looked at the “Specifying Conditional Headers for Blob Service Operations” MSDN topic, which says the following:

If-None-Match

An ETag value, or the wildcard character (). Specify this header to perform the operation only if the resource's ETag does not match the value specified.

Specify the wildcard character () to perform the operation only if the resource does not exist, and fail the operation if it does exist.

That means all we need to do to keep our Put Blob request from overwriting an existing file is to add the If-None-Match:* header to our request!

Here’s how to upload text to a blob without overwriting the existing contents:


try
{
    blob.UploadText("Hello, World!", Encoding.ASCII,
        new BlobRequestOptions() { AccessCondition = AccessCondition.IfNoneMatch("*") });
    Console.WriteLine("Wrote to blob.");
}
catch (StorageClientException e)
{
    if (e.ErrorCode == StorageErrorCode.BlobAlreadyExists)
    {
        Console.WriteLine("Blob already exists.");
    }
    else
    {
        throw;
    }
}