c# - 重命名 Azure 容器时出现 System.InvalidCastException
问题描述
我正在尝试重命名 azure blob 存储中的容器。我能够成功重命名容器。但我注意到在某些情况下,在某些过程中。我遇到了一些错误。
这是错误消息。
System.InvalidCastException:'无法将'Microsoft.WindowsAzure.Storage.Blob.CloudBlobDirectory'类型的对象转换为'Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob'类型。'
下面是我的代码。
string ContainerName = "old-container-name";
string NewContainerName = "new-container-name";
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(ContainerName);
CloudBlobContainer destcontainer = blobClient.GetContainerReference(NewContainerName);
destcontainer.CreateIfNotExists(BlobContainerPublicAccessType.Blob);
IEnumerable<IListBlobItem> IE = container.ListBlobs(blobListingDetails: BlobListingDetails.Metadata);
foreach (IListBlobItem item in IE)
{
CloudBlockBlob blob = (CloudBlockBlob)item;
CloudBlockBlob destBlob = destcontainer.GetBlockBlobReference(blob.Name);
destBlob.StartCopyAsync(new Uri(GetSharedAccessUri(blob.Name, container)));
}
我在这一行收到错误:
CloudBlockBlob blob = (CloudBlockBlob)item;
各位大佬有这个解决办法吗?有关如何解决此问题的任何提示?
解决方案
您收到此错误的原因是您列出 blob 的方式。
IEnumerable<IListBlobItem> IE = container.ListBlobs(blobListingDetails: BlobListingDetails.Metadata);
上面的代码行将列出 blob 和虚拟文件夹。虚拟文件夹由 表示CloudBlobDirectory
。由于您尝试将类型的对象转换CloudBlockBlob
为CloudBlobDirectory
,因此您会遇到此异常。
要列出 blob 容器中的所有 blob,请使用以下ListBlobs
方法覆盖:https ://docs.microsoft.com/en-us/dotnet/api/microsoft.azure.storage.blob.cloudblobcontainer.listblobs?view=azure -dotnet-legacy。
您将需要传递参数true
。useFlatBlobListing
然后它将只返回 blob 而不是虚拟文件夹。
推荐阅读
- javascript - 如何拥有一个可以排序的按钮和另一个可以反转文本字密度的按钮?
- java - 如何解决应用程序已停止?(appbarlayout 和 tablayout)
- airflow - 动态生成气流 DAG
- java - 使用“System.out.println("TEXT");”修复的 JAVA 奇怪错误
- javascript - 如何使用 useState 在反应功能组件的循环中正确设置状态
- python - 计算两条线之间的特定角度
- javascript - 无法提取 [Object, object] 值
- javascript - 以 rxjs 方式删除对象的一部分
- r - R:如果循环中使用的函数具有 stop() 子句,则继续循环到下一次迭代
- truffle - 部署智能合约时松露卡住了