首页 > 解决方案 > 重命名 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;

各位大佬有这个解决办法吗?有关如何解决此问题的任何提示?

标签: c#asp.netazureazure-blob-storage

解决方案


您收到此错误的原因是您列出 blob 的方式。

IEnumerable<IListBlobItem> IE = container.ListBlobs(blobListingDetails: BlobListingDetails.Metadata);

上面的代码行将列出 blob 和虚拟文件夹。虚拟文件夹由 表示CloudBlobDirectory。由于您尝试将类型的对象转换CloudBlockBlobCloudBlobDirectory,因此您会遇到此异常。

要列出 blob 容器中的所有 blob,请使用以下ListBlobs方法覆盖:https ://docs.microsoft.com/en-us/dotnet/api/microsoft.azure.storage.blob.cloudblobcontainer.listblobs?view=azure -dotnet-legacy

您将需要传递参数trueuseFlatBlobListing然后它将只返回 blob 而不是虚拟文件夹。


推荐阅读