如果存在,则打开块blob

时间:2014-10-11 12:26:14

标签: azure azure-storage

在一个场景中,我需要加载数百个Azure blob而不确定它们是否存在。

此代码执行2次往返服务器 - Exists中的一个 HEAD OpenRead中的一个 GET

CloudBlobContainer container = ... ;
Parallel.ForEach( ... => {
    string blobName = ... ;
    var blob = container.GetBlockBlobReference(blobName);
    if (blob.Exists()) {
        using (var stream = blob.OpenRead()) {
            ...
        }
     }
});

有可能......

  • 打开blob
  • 如果不存在则不会抛出异常
  • 单次往返服务器

...

2 个答案:

答案 0 :(得分:1)

您可以进行一次性点击以获取容器中的所有blob,然后在检索blob之前检查该列表。这是一个改编自我使用的方法的方法,它返回一个可用于快速列表查找的HashSet:

/// <summary>
/// Get the names of all blobs in a container and optionally containers with a
/// specific prefix.
/// </summary>
/// <param name="container">Name of Container to search</param>
/// <param name="prefix">Further filter where to search in container with a prefix.</param>
/// <returns>HashSet of string that names all blobs in container</returns>
public HashSet<string> GetBlobsInContainer(string container, string prefix)
{
  HashSet<string> theBlobs = new HashSet<string>();

  //GetStorageAcct returns CloudStorageAccount object
  CloudBlobClient blobClient = GetStorageAcct().CreateCloudBlobClient();
  CloudBlobContainer blobContainer = blobClient.GetContainerReference(container);

  foreach (IListBlobItem item in blobContainer.ListBlobs(prefix, true))
  {
    CloudBlockBlob cbb = (CloudBlockBlob)item;
    theBlobs.Add(cbb.Name);
  }

  return theBlobs;
}

答案 1 :(得分:0)

不,这是不可能的。最好的方法是不要调用Exists并捕获异常。如果您担心性能,请注意即使使用Exists调用也会从System.Net引发异常。但是,Azure存储客户端库通过向调用者返回false来捕获和处理它。

相关问题