C# 如何检查 Azure Blob 文件是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11032735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 16:12:33  来源:igfitidea点击:

How to check if Azure Blob file Exists or Not

c#azure-storageazure-storage-blobs

提问by Hope

I want to check a particular file exist in Azure Blob Storage. Is it possible to check by specifying it's file name? Each time i got File Not Found Error.

我想检查 Azure Blob 存储中是否存在特定文件。是否可以通过指定它的文件名来检查?每次我收到文件未找到错误。

采纳答案by Jakub Konecki

This extension method should help you:

此扩展方法应该可以帮助您:

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;
            }
        }
    }
}

Usage:

用法:

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.");
    }
}

http://blog.smarx.com/posts/testing-existence-of-a-windows-azure-blob

http://blog.smarx.com/posts/testing-existence-of-a-windows-azure-blob

回答by Babak Naffas

With the updated SDK, once you have the CloudBlobReference you can call Exists() on your reference.

使用更新后的 SDK,一旦您拥有 CloudBlobReference,您就可以对您的引用调用 Exists()。

UPDATE

更新

The relevant documentation has been moved to https://docs.microsoft.com/en-us/dotnet/api/microsoft.windowsazure.storage.blob.cloudblob.exists?view=azurestorage-8.1.3#Microsoft_WindowsAzure_Storage_Blob_CloudBlob_Exists_Microsoft_WindowsAzure_Storage_Blob_BlobRequestOptions_Microsoft_WindowsAzure_Storage_OperationContext_

相关文档已移至https://docs.microsoft.com/en-us/dotnet/api/microsoft.windowsazure.storage.blob.cloudblob.exists?view=azurestorage-8.1.3#Microsoft_WindowsAzure_Storage_Blob_CloudBlob_Exists_Microsoft_WindowsAzure_Storage_Blob_Blobation_MicrosoftOperationAzure_Microsoft

My implementation using WindowsAzure.Storage v2.0.6.1

我使用 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();
    }

回答by sam

var blob = client.GetContainerReference(containerName).GetBlockBlobReference(blobFileName);

if (blob.Exists())
 //do your stuff

回答by d.popov

Using Microsoft.WindowsAzure.Storage.Blob version 4.3.0.0, the following code should work (there are a lot of breaking changes with older versions of this assembly):

使用Microsoft.WindowsAzure.Storage.Blob 版本 4.3.0.0,以下代码应该可以工作(此程序集的旧版本有很多重大更改):

Using container/blob name, and the given API (seems now Microsoft have actualy implemented this):

使用容器/blob 名称和给定的 API(现在微软似乎已经实现了这一点):

return _blobClient.GetContainerReference(containerName).GetBlockBlobReference(blobName).Exists();

Using blob URI (workaround):

使用 blob URI(解决方法):

  try 
  {
      CloudBlockBlob cb = (CloudBlockBlob) _blobClient.GetBlobReferenceFromServer(new Uri(url));
      cb.FetchAttributes();
  }
  catch (StorageException se)
  {
      if (se.Message.Contains("404") || se.Message.Contains("Not Found"))
      {
          return false;
      }
   }
   return true;

(Fetch attributes will fail if the blob is not existing. Dirty, I know :)

(如果 blob 不存在,获取属性将失败。脏,我知道 :)

回答by user3613932

Use the ExistsAsyncmethod of CloudBlockBlob.

使用ExistsAsyncCloudBlockBlob的方法。

bool blobExists = await cloudBlobContainer.GetBlockBlobReference("<name of blob>").ExistsAsync();

回答by rc125

Using the new package Azure.Storage.Blobs

使用新包 Azure.Storage.Blobs

BlobServiceClient blobServiceClient = new BlobServiceClient("YourStorageConnectionString");
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient("YourContainerName");
BlobClient blobClient = containerClient.GetBlobClient("YourFileName");

then check if exists

然后检查是否存在

if (blobClient.Exists()){
 //your code
}