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

27

我想要检查Azure Blob存储中是否存在特定的文件。是否可以通过指定文件名进行检查?每次都会出现“文件未找到”错误。


1
我认为这个问题是这个的重复 https://dev59.com/YnE85IYBdhLWcg3wtV_1 去看看吧。 - Marco Staffoli
这个回答解决了你的问题吗?在Azure存储中检查blob是否存在 - Michael Freidgeim
9个回答

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

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

13
尝试为您的代码添加一些上下文,以帮助提问者更好地理解。 - Bjorn

18

这个扩展方法应该对你有帮助:

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 的存在。 - Jakub Konecki
3
注意:这个方案已经不能用于新的SDK。其他答案是解决方案。 - Tincan

14

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

更新

相关文档已移至https://learn.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();
    }

3
但它总是返回 false。有人遇到过相同的问题吗? - d.popov
1
@d.popov - 我这里也有同样的问题。已验证文件确实存在,但exists()始终返回false。还没有解决这个问题... - Steve
这个问题解决了吗?对我来说,Exists 总是返回“false”。 - Adam Levitt
1
@AdamLevitt 我已经更新了答案,并使用Exists方法实现了我的代码。这个方法在我生产环境中使用了几年,一直很稳定。 - Babak Naffas
1
@AdamLevitt 确保这不是大小写问题。 - Babak Naffas
显示剩余6条评论

5
使用新的包Azure.Storage.Blobs
BlobServiceClient blobServiceClient = new BlobServiceClient("YourStorageConnectionString");
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient("YourContainerName");
BlobClient blobClient = containerClient.GetBlobClient("YourFileName");

然后检查是否存在

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

4
使用 CloudBlockBlob 的 ExistsAsync 方法。
bool blobExists = await cloudBlobContainer.GetBlockBlobReference("<name of blob>").ExistsAsync();

3
使用 Microsoft.WindowsAzure.Storage.Blob 版本 4.3.0.0,下面的代码应该可以工作(旧版本的这个程序集有很多破坏性变化):
使用容器/ blob 名称和给定的 API (看起来现在 Microsoft 已经实现了这个):
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,这有帮助吗?您使用的存储客户端版本是什么? - d.popov
"Microsoft.WindowsAzure.Storage.StorageException"具有"RequestInformation.HttpStatusCode"。对于不存在的blob,它将会是HTTP / 404。 - Jari Turkia

2
使用最新版本的SDK,您需要使用ExistsAsync方法。
public async Task<bool> FileExists(string fileName)
{
    return  await directory.GetBlockBlobReference(fileName).ExistsAsync();
}

这里是代码示例

1
这个完整的示例旨在帮助您。
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();

    }

}

那么你可以在主程序中进行测试。

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

重要提示:我发现文件名区分大小写。


0
## 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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接