How do I upload to Azure Blob storage without overwriting?

Rob Church picture Rob Church · Feb 18, 2013 · Viewed 8.1k times · Source

Calling UploadFromStream overwrites files by default - how can I make sure I only upload a blob if it isn't already in the container?

CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);
blockBlob.UploadFromStream(stream)

Answer

Rob Church picture Rob Church · Feb 18, 2013

Add an access condition to the code so that it checks against the ETag property of the blob - wildcards are allowed, so we want to only allow the upload if no blobs with this name have any etag (which is a roundabout way of saying, does this blob name exist).

You get a StorageException as detailed below.

    CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);
    try {
        blockBlob.UploadFromStream(stream, accessCondition: AccessCondition.GenerateIfNoneMatchCondition("*"));
    } catch (StorageException ex) {
        if (ex.RequestInformation.HttpStatusCode == (int)System.Net.HttpStatusCode.Conflict) {
            // Handle duplicate blob condition
        }
        throw;
    }