[英]Checking if container and blob exist in Azure Blob Storage using built in Exists method
[英]Checking if a blob exists in Azure Storage
我有一個非常簡單的問題(我希望!) - 我只想找出特定容器中是否存在 blob(具有我定義的名稱)。 如果它確實存在,我會下載它,如果它不存在,那么我會做其他事情。
我已經對 intertubes 進行了一些搜索,顯然曾經有一個名為 DoesExist 或類似的函數……但與許多 Azure API 一樣,這似乎不再存在(或者如果存在,非常巧妙地偽裝的名字)。
新 API 具有 .Exists() 函數調用。 只需確保您使用GetBlockBlobReference
,它不會執行對服務器的調用。 它使功能變得如此簡單:
public static bool BlobExistsOnCloud(CloudBlobClient client,
string containerName, string key)
{
return client.GetContainerReference(containerName)
.GetBlockBlobReference(key)
.Exists();
}
注意:這個答案現在已經過時了。 請參閱 Richard 的回答,了解檢查是否存在的簡單方法
不,您並沒有遺漏一些簡單的東西……我們很好地將這個方法隱藏在新的 StorageClient 庫中。 :)
我剛剛寫了一篇博文來回答你的問題: http : //blog.smarx.com/posts/testing-existence-of-a-windows-azure-blob 。
簡短的回答是:使用 CloudBlob.FetchAttributes(),它對 blob 執行 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;
}
}
}
如果 blob 是公開的,你當然可以只發送一個 HTTP HEAD 請求——來自無數知道如何做到這一點的語言/環境/平台中的任何一個——並檢查響應。
核心 Azure API 是基於 RESTful 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 是微不足道的。
新的 Windows Azure 存儲庫已包含 Exist() 方法。 它位於 Microsoft.WindowsAzure.Storage.dll 中。
可用作 NuGet 包
創建者:微軟
Id:WindowsAzure.Storage
版本:2.0.5.1
如果您不喜歡其他解決方案,這里有一個不同的解決方案:
我使用的是 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;
}
}
}
希望這對將來的人有所幫助。
如果您的 blob 是公開的並且您只需要元數據:
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
如果您不喜歡使用異常方法,那么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,您就可以對您的引用調用 Exists()。
這就是我這樣做的方式。 為需要的人顯示完整的代碼。
// 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 調用應始終異步完成,並且在這種情況下,SDK 完全支持它。 只需使用ExistsAsync()
而不是Exists()
。
bool exists = await client.GetContainerReference(containerName)
.GetBlockBlobReference(key)
.ExistsAsync();
借助 Azure Blob 存儲庫 v12,可以使用BlobBaseClient.Exists()/BlobBaseClient.ExistsAsync()
回答了另一個類似的問題: https : //stackoverflow.com/a/63293998/4865541
Java 版本相同(使用新的 v12 SDK)
這使用共享密鑰憑據授權,即帳戶訪問密鑰。
StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey);
String endpoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", accountName);
BlobServiceClient storageClient = new BlobServiceClientBuilder().credential(credential)
.endpoint(endpoint).buildClient();
BlobContainerClient container = storageClient.getBlobContainerClient(containerName)
if ( container.exists() ) {
// perform operation when container exists
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.