Joh*_*ohn 119 c# azure azure-blob-storage
我有一个非常简单的问题(我希望!) - 我只是想知道一个特定容器中是否存在一个blob(我已经定义了一个名字).我会下载它,如果它确实存在,如果它不存在,那么我会做其他事情.
我已经对intertubes进行了一些搜索,显然曾经有一个名为DoesExist的函数或类似的东西......但是就像许多Azure API一样,这似乎不再存在(或者如果有的话)非常巧妙伪装的名字).
Ric*_*ard 192
新API具有.Exists()函数调用.只需确保使用GetBlockBlobReference不执行对服务器的调用的.它使功能像以下一样简单:
public static bool BlobExistsOnCloud(CloudBlobClient client,
string containerName, string key)
{
return client.GetContainerReference(containerName)
.GetBlockBlobReference(key)
.Exists();
}
Run Code Online (Sandbox Code Playgroud)
use*_*559 49
注意:这个答案现在已经过时了.请查看理查德的答案,以便检查存在的简便方法
不,你不会错过一些简单的东西......我们很好地将这个方法隐藏在新的StorageClient库中.:)
我刚写了一篇博文来回答你的问题:http://blog.smarx.com/posts/testing-existence-of-a-windows-azure-blob.
简短的回答是:使用CloudBlob.FetchAttributes(),它对blob执行HEAD请求.
小智 16
看起来很蹩脚,你需要捕获一个异常来测试blob是否存在.
public static bool Exists(this CloudBlob blob)
{
try
{
blob.FetchAttributes();
return true;
}
catch (StorageClientException e)
{
if (e.ErrorCode == StorageErrorCode.ResourceNotFound)
{
return false;
}
else
{
throw;
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 9
如果blob是公共的,你当然可以发送一个HTTP HEAD请求 - 来自任何知道如何做的数十种语言/环境/平台 - 并检查响应.
核心Azure API是基于REST的XML的HTTP接口.StorageClient库是围绕它们的许多可能包装器之一.这是Sriram Krishnan在Python中做的另一个:
http://www.sriramkrishnan.com/blog/2008/11/python-wrapper-for-windows-azure.html
它还显示了如何在HTTP级别进行身份验证.
我在C#中为自己做了类似的事情,因为我更喜欢通过HTTP/REST的镜头而不是通过StorageClient库的镜头来看Azure.很长一段时间,我甚至都不愿意实施ExistsBlob方法.我的所有blob都是公开的,做HTTP HEAD是微不足道的.
如果您不喜欢其他解决方案,这里有一个不同的解决方案:
我使用的是 Azure.Storage.Blobs NuGet 包的版本 12.4.1。
我得到一个Azure.Pageable对象,它是容器中所有 blob 的列表。然后,我使用LINQ检查BlobItem的名称是否等于容器内每个 Blob 的Name属性。(当然,如果一切都有效的话)
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using System.Linq;
using System.Text.RegularExpressions;
public class AzureBlobStorage
{
private BlobServiceClient _blobServiceClient;
public AzureBlobStorage(string connectionString)
{
this.ConnectionString = connectionString;
_blobServiceClient = new BlobServiceClient(this.ConnectionString);
}
public bool IsContainerNameValid(string name)
{
return Regex.IsMatch(name, "^[a-z0-9](?!.*--)[a-z0-9-]{1,61}[a-z0-9]$", RegexOptions.Singleline | RegexOptions.CultureInvariant);
}
public bool ContainerExists(string name)
{
return (IsContainerNameValid(name) ? _blobServiceClient.GetBlobContainerClient(name).Exists() : false);
}
public Azure.Pageable<BlobItem> GetBlobs(string containerName, string prefix = null)
{
try
{
return (ContainerExists(containerName) ?
_blobServiceClient.GetBlobContainerClient(containerName).GetBlobs(BlobTraits.All, BlobStates.All, prefix, default(System.Threading.CancellationToken))
: null);
}
catch
{
throw;
}
}
public bool BlobExists(string containerName, string blobName)
{
try
{
return (from b in GetBlobs(containerName)
where b.Name == blobName
select b).FirstOrDefault() != null;
}
catch
{
throw;
}
}
}
Run Code Online (Sandbox Code Playgroud)
希望这对将来的人有帮助。
| 归档时间: |
|
| 查看次数: |
63524 次 |
| 最近记录: |