[英]Trying to delete an Azure blob - getting blob does not exist exception
我有一個帶有 blob (/images/filename) 的 Azure 存儲容器。 文件名(uri)在創建時存儲在數據庫中,來自文件上傳保存function:
blob.UploadFromStream(filestream);
string uri = blob.Uri.AbsoluteUri;
return uri;
文件上傳工作正常,當通過 SAS 密鑰下載傳遞給客戶端時也工作正常。
要刪除圖像,我有一個助手 function 取自此處的 MS 示例: MS Github 示例這是 function:
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;
}
}
這一切都在一個助手 class 中,其開頭如下:
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 等。
我想知道這是否可能是權限問題? 還是我錯過了其他東西?
我認為您的容器中有一個目錄。 假設您有一個名為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();
或使用此代碼段:
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();
似乎是權限問題,您可以轉到門戶,然后在 azure bolb 存儲上編輯容器元數據。 將訪問 private 更改為public
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.