c# - 尝试删除 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 等。
我想知道这是否可能是权限问题?还是我错过了其他东西?
解决方案
我认为您的容器中有一个目录。假设您有一个名为 的容器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();
推荐阅读
- c# - Application Insights 开发人员模式在 ASP.NET Core 3.1 中不起作用
- machine-learning - 使用 SMOTE 过采样从 y_train 中删除标签类别
- c# - 如何从项目列表中生成多个表单?
- google-cloud-dataflow - GCP 数据流 - 吞吐量逐渐减慢,工作人员未充分利用
- spring-boot - 尝试在 Java Spring Boot 中从 H2 数据库中获取相关实体
- ansible - 单个项目和项目列表的循环和 with_items 行为之间的区别
- html - 将css文件链接到html文件时的根目录
- python - OpenCV - 从二维图像点正确恢复姿势和地标位置
- r - 反转变量列表的值
- python - 尝试绘制一个对象:使用 matplotlib 在数据集中列出日期列