【问题标题】:How to check if Azure Blob file Exists or Not如何检查 Azure Blob 文件是否存在
【发布时间】:2012-06-17 11:09:16
【问题描述】:

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

【问题讨论】:

标签: c# azure-storage azure-blob-storage


【解决方案1】:

这个扩展方法应该可以帮助你:

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

用法:

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

【讨论】:

  • 是的,但我认为没有其他方法可以检查 blob 是否存在。
  • 注意:这不再适用于新的 SDK。其他答案就是解决方案。
【解决方案2】:

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

更新

相关文档已移至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_

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

【讨论】:

  • 但它总是返回 false。有人遇到同样的问题吗?
  • 验证您的存储桶和文件本身的可见性。如果它是公开可见的,请尝试通过浏览器访问它。可能是您的 URI 不正确。
  • @d.popov - 我在这里遇到了同样的问题。已验证文件确实存在,但 exists() 始终返回 false。还没解决问题...
  • @AdamLevitt 我已经使用 Exists 方法更新了我的实现的答案。这已经在生产中为我工作了几年。
  • @AdamLevitt 确保不是大小写问题。
【解决方案3】:
var blob = client.GetContainerReference(containerName).GetBlockBlobReference(blobFileName);

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

【讨论】:

  • 尝试为您的代码添加一些上下文以帮助提出问题的人。
【解决方案4】:

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

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

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

使用 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;

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

【讨论】:

  • @Steve,这有帮助吗?您使用的是什么版本的存储客户端?
  • Microsoft.WindowsAzure.Storage.StorageExceptionRequestInformation.HttpStatusCode。对于不存在的 blob,它将是 HTTP/404。
【解决方案5】:

使用 CloudBlockBlob 的ExistsAsync 方法。

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

【讨论】:

    【解决方案6】:

    使用新包Azure.Storage.Blobs

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

    然后检查是否存在

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

    【讨论】:

      【解决方案7】:

      使用最新版本的SDK,需要使用ExistsAsync方法,

      public async Task<bool> FileExists(string fileName)
      {
          return  await directory.GetBlockBlobReference(fileName).ExistsAsync();
      }
      

      这里是code sample

      【讨论】:

        【解决方案8】:
        ## dbutils.widgets.get to call the key-value from data bricks job
        
        storage_account_name= dbutils.widgets.get("storage_account_name")
        container_name= dbutils.widgets.get("container_name")
        transcripts_path_intent= dbutils.widgets.get("transcripts_path_intent")
        # Read azure blob access key from dbutils 
        storage_account_access_key = dbutils.secrets.get(scope = "inteliserve-blob-storage-secret-scope", key = "storage-account-key")
        
        from azure.storage.blob import BlockBlobService
        block_blob_service = BlockBlobService(account_name=storage_account_name, account_key=storage_account_access_key)
        
        def blob_exists():
                container_name2 = container_name
                blob_name = transcripts_path_intent
                exists=(block_blob_service.exists(container_name2, blob_name))
                return exists
        blobstat = blob_exists()
        print(blobstat)
        

        【讨论】:

          【解决方案9】:

          这个完整的例子可以提供帮助。

          public class TestBlobStorage
          {
          
              public bool BlobExists(string containerName, string blobName)
              {
                  BlobServiceClient blobServiceClient = new BlobServiceClient(@"<connection string here>");
          
                  var container = blobServiceClient.GetBlobContainerClient(containerName);
                  
                  var blob = container.GetBlobClient(blobName);
          
                  return blob.Exists();
          
              }
          
          }
          

          然后你可以在 main 中测试

              static void Main(string[] args)
              {
          
                  TestBlobStorage t = new TestBlobStorage();
          
                  Console.WriteLine("blob exists: {0}", t.BlobExists("image-test", "AE665.jpg")); 
          
                  Console.WriteLine("--done--");
                  Console.ReadLine();
              }
          

          重要我发现文件名区分大小写

          【讨论】:

            猜你喜欢
            • 2011-10-14
            • 1970-01-01
            • 1970-01-01
            • 2013-07-05
            • 2011-02-08
            • 1970-01-01
            • 2017-11-02
            • 1970-01-01
            • 2020-07-22
            相关资源
            最近更新 更多