【问题标题】:ListBlobs() sees only the first folder in the Azure blob containerListBlobs() 仅查看 Azure blob 容器中的第一个文件夹
【发布时间】:2020-03-11 21:37:02
【问题描述】:

我的 Azure Blob 容器包含两个虚拟文件夹 A 和 B,以及一些文件。我在我的项目中使用此代码来下载本地文件夹中容器的内容:

private async void Test(string temp, CloudBlobContainer container, string target, string prefix) {
   foreach (var item in container.ListBlobs(prefix)) {
      switch (item) {
         case CloudBlobDirectory directory:
            Directory.CreateDirectory(Path.Combine(temp, directory.Prefix));
            Test(Path.Combine(temp, directory.Prefix), container, target, directory.Prefix);
            break;
      }
   }
   await CopyAll(temp, target, controller); /* Just a function to call at the end of the method*/
}

拥有一个具有这种虚拟结构的容器:

container
   A/
   B/
   one.txt
   two.txt
   ...

我想在本地文件夹上复制相同的结构。问题是 B 被跳过 并且 foreach 只考虑 A,但是如果我将 Test(Path.Combine(temp, directory.Prefix), container, target, directory.Prefix) 替换为例如 System.Diagnostics.Debug.WriteLine(directory.Prefix) 以仅打印它们,则 B 被打印到控制台。很明显递归存在问题,但我看不到它。我使用递归来遍历容器中的虚拟目录,以便将原始结构复制到本地文件夹中。

【问题讨论】:

    标签: c# recursion azure-blob-storage


    【解决方案1】:

    你应该粘贴完整的代码,我们不知道你的帖子中的Test()/CopyAll()这些函数的细节。

    但是如果你想下载所有的blob(包括文件夹),并在本地保持相同的结构,你可以试试下面的代码:

     var conn_str = "DefaultEndpointsProtocol=https;AccountName=xxx;AccountKey=xxx;EndpointSuffix=core.windows.net";
     var myContainer = "aaa";
    
     CloudStorageAccount storageAccount = CloudStorageAccount.Parse(conn_str);
     CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
     CloudBlobContainer blobContainer = blobClient.GetContainerReference(myContainer);
    
     var blobs = blobContainer.ListBlobs(prefix:null,useFlatBlobListing:true);
    
           
     foreach (var item in blobs)
     {
        switch (item) {
            case CloudBlockBlob blob:
                var filename = blob.Uri.Segments.Last();
    
                //download the blobs which directly under the container
                if (string.IsNullOrEmpty(blob.Parent.Prefix))
                {
                    blob.DownloadToFile(@"d:\aaa" + "\\" + filename, FileMode.CreateNew);
                }
                else
                {
                    //download the blobs which are inside folder
                    string a = Path.Combine(@"d:\aaa", blob.Parent.Prefix);
    
                    var mydiretory = Directory.CreateDirectory(a);
                    blob.DownloadToFile(mydiretory.FullName + filename, FileMode.CreateNew);
                }
                break;
            default:
                break;
        }
    }
    

    我正在使用这个 nuget 包Microsoft.Azure.Storage.Blob, version 11.1.3

    如果您对此还有更多问题,请告诉我。

    【讨论】:

    • 谢谢!我仍然无法弄清楚为什么我的代码不起作用。
    猜你喜欢
    • 2018-04-13
    • 2020-02-14
    • 2016-04-16
    • 1970-01-01
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    • 2018-07-08
    • 2016-11-29
    相关资源
    最近更新 更多