检查 Azure 存储中是否存在 blob
-
27-09-2019 - |
题
我有一个非常简单的问题(我希望如此!) - 我只想查明某个 blob(具有我定义的名称)是否存在于特定容器中。如果它确实存在,我会下载它,如果不存在,我会做其他事情。
我在管间做了一些搜索,显然曾经有一个名为DoesExist或类似的函数......但与许多 Azure API 一样,它似乎不再存在(或者即使存在,也有一个非常巧妙伪装的名称)。
解决方案
在新的API具有.Exists()函数调用。只要确保您使用GetBlockBlobReference
,不执行调用服务器。它使功能一样简单:
public static bool BlobExistsOnCloud(CloudBlobClient client,
string containerName, string key)
{
return client.GetContainerReference(containerName)
.GetBlockBlobReference(key)
.Exists();
}
其他提示
注意:这个答案是过时了。请参阅理查德的回答一个简单的方法来检查是否存在
没有,你不是简单的东西......我们做了新的StorageClient库中隐藏这种方法的一个好工作。 :)
我刚刚写了一篇博客来回答你的问题:的 http://blog.smarx.com/posts/testing-existence-of-a-windows-azure-blob 。
简短的回答是:使用CloudBlob.FetchAttributes(),它确实对团块HEAD请求
看起来很蹩脚,您需要捕获异常来测试 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;
}
}
}
如果斑是公开的,你可以,当然,只是发送一个HTTP HEAD请求 - 从任何语言/环境/平台,知道该怎么做了不计其数的 - 和检查响应
核心天青API是RESTful的基于XML的HTTP接口。该StorageClient库是他们周围很多可能的包装之一。这里是另一种斯利拉姆克里希南在Python做的:
HTTP://www.sriramkrishnan。 COM /博客/ 2008/11 /蟒-包装换窗口-azure.html
它还示出了如何在HTTP级别进行认证。
我已经做了我自己类似的事情,在C#中,因为我更喜欢REST,而不是通过StorageClient库的镜头/看天青通过HTTP的镜头。有一段时间我什至没有费心去实现一个ExistsBlob方法。我所有的斑点是公开的,这是容易做到的HTTP头。
在新的Windows Azure存储库中已经包含了存在()方法。 It's在Microsoft.WindowsAzure.Storage.dll。
可作为NuGet包,点击 创建者:微软点击 ID:WindowsAzure.Storage结果 版本:2.0.5.1
如果你不喜欢使用异常的方法则judell暗示什么基本的C#版本如下。虽然小心,你真的应该来处理其他可能的反应了。
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
myReq.Method = "HEAD";
HttpWebResponse myResp = (HttpWebResponse)myReq.GetResponse();
if (myResp.StatusCode == HttpStatusCode.OK)
{
return true;
}
else
{
return false;
}
通过更新的SDK,一旦你有,你可以调用CloudBlobReference是否存在()在你的参考。
这是我这样做的方式。显示完整的代码对于那些谁需要它。
// Parse the connection string and return a reference to the storage account.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("AzureBlobConnectionString"));
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference("ContainerName");
// Retrieve reference to a blob named "test.csv"
CloudBlockBlob blockBlob = container.GetBlockBlobReference("test.csv");
if (blockBlob.Exists())
{
//Do your logic here.
}
虽然大多数的答案这里在技术上是正确的,最代码样本正在同步/阻塞调用。除非你是一个很老的平台或代码库的约束,HTTP调用应的总是的被asynchonously做的,而SDK完全支持它在这种情况下。只需使用ExistsAsync()
代替Exists()
。
bool exists = await client.GetContainerReference(containerName)
.GetBlockBlobReference(key)
.ExistsAsync();
如果你的斑点是公开的,你只需要元数据:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "HEAD";
string code = "";
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
code = response.StatusCode.ToString();
}
catch
{
}
return code; // if "OK" blob exists