首页 > 解决方案 > 尝试删除 Azure blob - 获取 blob 不存在异常

问题描述

我有一个带有 blob (/images/filename) 的 Azure 存储容器。文件名(uri)在创建时存储在数据库中,来自文件上传保存函数:

        blob.UploadFromStream(filestream);
        string uri = blob.Uri.AbsoluteUri;
        return uri;

文件上传工作正常,当通过 SAS 密钥下载传递给客户端时也工作正常。

要删除图像,我有一个从 MS 示例中获取的辅助函数:MS Github 示例 这里是函数:

    internal bool DeleteFile(string fileURI)
    {
        try
        {
            Uri uri = new Uri(fileURI);
            string filename = Path.GetFileName(uri.LocalPath);
            CloudBlockBlob fileblob = container.GetBlockBlobReference(filename);
            fileblob.Delete();
            bool res = fileblob.DeleteIfExists();
            return res; //Ok
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex);
            return false;
        }

    }

这一切都在一个助手类中,其开头如下:

public class AzureHelpers
{
    private string connection;
    private CloudStorageAccount storageAccount;
    private CloudBlobClient blobClient;
    private CloudBlobContainer container;


    public AzureHelpers()
    {
        connection = CloudConfigurationManager.GetSetting("myproject_AzureStorageConnectionString");
        storageAccount = CloudStorageAccount.Parse(connection);
        blobClient = storageAccount.CreateCloudBlobClient();
        container = blobClient.GetContainerReference(Resources.DataStoreRoot);
        container.CreateIfNotExists();
    }
 ....

我故意在 deleteIfExists 之前添加了删除以导致异常并证明我怀疑它没有找到文件/blob。

然而,当我单步执行代码时,CloudBlockBlob 肯定存在并且具有正确的 URI 等。

我想知道这是否可能是权限问题?还是我错过了其他东西?

标签: c#azureazure-blob-storage

解决方案


我认为您的容器中有一个目录。假设您有一个名为 的容器container_1,并且您的文件存储在/images/a.jpg. 在这里您应该记住,在这种情况下,您的 blob 名称是images/a.jpg,而不是a.jpg

在您的代码中,Path.GetFileName仅获取文件名 like a.jpg,因此它与真实的 blob name 不匹配images/a.jpg,从而导致错误“不存在”。

所以在你的DeleteFile(string fileURI)方法中,试试下面的代码,它在我身边工作得很好:

Uri uri = new Uri(fileURI);
var temp = uri.LocalPath;
string filename = temp.Remove(0, temp.IndexOf('/', 1)+1);
CloudBlockBlob fileblob = container.GetBlockBlobReference(filename);
//fileblob.Delete();
bool res = fileblob.DeleteIfExists();

或使用此代码段:

Uri uri = new Uri(fileURI);

//use this line of code just to get the blob name correctly
CloudBlockBlob blob_temp = new CloudBlockBlob(uri);

var myblob = cloudBlobContainer.GetBlockBlobReference(blob_temp.Name);
bool res = myblob.DeleteIfExists();

推荐阅读