如何一步异步下载 Azure blob(仅当它存在时)?

Mat*_*int 5 stream azure-storage async-await

我想从 Azure 存储异步下载块 blob,但前提是该 blob 存在。

var blob = documentsContainer.GetBlockBlobReference(blobName);
if (await blob.ExistsAsync())
    await blob.DownloadToStreamAsync(stream);
Run Code Online (Sandbox Code Playgroud)

但这会产生两次 HTTP 调用,对吧?我的应用程序中的常见路径是 blob 将存在,因此大多数时候我不希望存在检查的开销。但我需要优雅地处理该斑点也不存在的情况。

我尝试保留存在检查并仅使用 try/catch 块。如果我使用DownloadTextAsync,那么这是有效的,但是当使用 时DownloadToStreamAsync,如果斑点不存在,它就会挂起。

有没有办法将二进制 blob 异步下载到流(仅当它存在时),而不进行两次调用?

Mat*_*int 2

事实证明它确实正确地抛出了异常:

try
{
    var blob = documentsContainer.GetBlockBlobReference(blobName);
    await blob.DownloadToStreamAsync(stream);
    ...
}
catch (StorageException ex)
{
    if ((HttpStatusCode)ex.RequestInformation.HttpStatusCode == HttpStatusCode.NotFound)
    {
        return null;  // exit the calling function
    }

    throw;
}
Run Code Online (Sandbox Code Playgroud)

当我最初尝试这个时,它在DownloadToStreamAsync通话时挂起。在原始问题中发表评论后,我开始检查版本,发现 Microsoft.Data.Services.Client.dll 不匹配。我使用的是 5.6.1,但我的测试项目不知何故有 5.6.0。(我不确定它是从哪里获取的,因为它根本不在我的解决方案中)。从测试项目中手动引用 Microsoft.Data.Services.Client 5.6.1 后,它不再挂起。