尝试删除 Azure blob - 获取 blob 不存在异常

Bre*_* JB 1 c# azure azure-blob-storage

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

        blob.UploadFromStream(filestream);
        string uri = blob.Uri.AbsoluteUri;
        return uri;
Run Code Online (Sandbox Code Playgroud)

文件上传工作正常,当使用 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;
        }

    }
Run Code Online (Sandbox Code Playgroud)

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

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();
    }
 ....
Run Code Online (Sandbox Code Playgroud)

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

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

我想知道这是否可能是权限问题?或者我还缺少其他东西吗?

Iva*_*ang 6

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

在您的代码中,Path.GetFileName仅获取诸如 之类的文件名a.jpg,因此它与真正的 blob 名称不匹配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();
Run Code Online (Sandbox Code Playgroud)

或使用以下代码片段:

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();
Run Code Online (Sandbox Code Playgroud)