Reputation: 6943
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)
Upvotes: 26
Views: 9979
Reputation: 6943
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;
}
Upvotes: 24
Reputation: 864
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);
Upvotes: 11
Reputation: 970
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;
}
Upvotes: 3