How do I upload to Azure Blob storage without overwriting?
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; }
Azure now has an access condition that will only add, not overwrite: AccessCondition.GenerateIfNotExistsCondition()
Definition:
Constructs an access condition such that an operation will be performed only if the resource does not exist.
Example:
var accessCondition = AccessCondition.GenerateIfNotExistsCondition();blockBlob.UploadFromStream(stream, accessCondition);
The answer provided by Rob Church seems ok. Checking strings for errors isn't best practice and be improved with:
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; }