默认情况下,调用UploadFromStream会覆盖文件 - 如果blob不在容器中,我怎样才能确保我只上传blob?
CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);
blockBlob.UploadFromStream(stream)
答案 0 :(得分:15)
为代码添加一个访问条件,以便检查blob的ETag属性 - 允许使用通配符,因此如果没有带有此名称的blob具有任何etag,则我们只希望允许上载(这是一种迂回的说法,这个blob名称是否存在)。
您将获得StorageException,如下所述。
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;
}
答案 1 :(得分:7)
Azure现在有一个访问条件,只会添加,而不是覆盖:AccessCondition.GenerateIfNotExistsCondition()
定义:
构造一个访问条件,以便仅在资源不存在时才执行操作。
示例:
var accessCondition = AccessCondition.GenerateIfNotExistsCondition();
blockBlob.UploadFromStream(stream, accessCondition);
答案 2 :(得分:4)
Rob Church提供的答案似乎没问题。检查字符串是否错误不是最佳做法,可以通过以下方式进行改进:
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;
}
答案 3 :(得分:-2)
您还可以检查blob是否存在,然后上传,如下所示:
CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);
if (!blockBlob.Exists())
{
blockBlob.UploadFromStream(stream)
}
如果您没有Exists方法,请查看此答案Checking if a blob exists in Azure Storage。