Hop*_*ope 14 c# azure-storage azure-storage-blobs
我想检查Azure Blob存储中是否存在特定文件.是否可以通过指定文件名进行检查?每次我得到文件未找到错误.
小智 28
var blob = client.GetContainerReference(containerName).GetBlockBlobReference(blobFileName);
if (blob.Exists())
//do your stuff
Run Code Online (Sandbox Code Playgroud)
Jak*_*cki 15
此扩展方法应该可以帮助您:
public static class BlobExtensions
{
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)
用法:
static void Main(string[] args)
{
var blob = CloudStorageAccount.DevelopmentStorageAccount
.CreateCloudBlobClient().GetBlobReference(args[0]);
// or CloudStorageAccount.Parse("<your connection string>")
if (blob.Exists())
{
Console.WriteLine("The blob exists!");
}
else
{
Console.WriteLine("The blob doesn't exist.");
}
}
Run Code Online (Sandbox Code Playgroud)
http://blog.smarx.com/posts/testing-existence-of-a-windows-azure-blob
使用更新的SDK,一旦您拥有CloudBlobReference,您就可以在引用上调用Exists().
UPDATE
我使用WindowsAzure.Storage v2.0.6.1实现
private CloudBlockBlob GetBlobReference(string filePath, bool createContainerIfMissing = true)
{
CloudBlobClient client = _account.CreateCloudBlobClient();
CloudBlobContainer container = client.GetContainerReference("my-container");
if ( createContainerIfMissing && container.CreateIfNotExists())
{
//Public blobs allow for public access to the image via the URI
//But first, make sure the blob exists
container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
}
CloudBlockBlob blob = container.GetBlockBlobReference(filePath);
return blob;
}
public bool Exists(String filepath)
{
var blob = GetBlobReference(filepath, false);
return blob.Exists();
}
Run Code Online (Sandbox Code Playgroud)
使用新包Azure.Storage.Blobs
BlobServiceClient blobServiceClient = new BlobServiceClient("YourStorageConnectionString");
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient("YourContainerName");
BlobClient blobClient = containerClient.GetBlobClient("YourFileName");
Run Code Online (Sandbox Code Playgroud)
然后检查是否存在
if (blobClient.Exists()){
//your code
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26652 次 |
| 最近记录: |