使用 .NET SDK 12 从 Azure Blob 存储中的特定目录/文件夹获取文件

Yza*_*zak 5 .net azure azure-blob-storage

我需要列出“Test”文件夹中特定目录中的所有文件,不包括“Test2”。我尝试使用“test”作为前缀,但它返回两个文件夹。

容器:“myContainer”

测试:

  • 文件1.jpg
  • 文件2.jpg

测试2:

  • 文件1.jpg

我尝试了以下操作,但它返回带有输出的文件夹和路径:

  • 测试/file1.jpg
  • 测试/file2.jpg
  • 测试2/文件1.jpg

我可以只返回文件而不是路径吗?

  • 文件1.jpg

  • 文件2.jpg

         var blobUri = new Uri($"https://{myAccountName}.blob.core.windows.net/");
         StorageSharedKeyCredential credential = new StorageSharedKeyCredential(myAccountName, myKey);
         BlobServiceClient service = new BlobServiceClient(blobUri, credential);
         BlobContainerClient container = service.GetBlobContainerClient("myContainer");
         AsyncPageable<BlobItem> blobs = container.GetBlobsAsync(prefix: "test");
    
         List<Result> results = new List<Result>();
         await foreach (var blob in blobs)
         {
             var result = new Result();
             result.FileName = blob.Name;
             results.Add(result);
         }
    
    Run Code Online (Sandbox Code Playgroud)

1_1*_*1_1 5

您可以测试下面的代码:

using Azure.Identity;
using Azure.Storage;
using Azure.Storage.Blobs;
using Azure.Storage.Files.DataLake;
using System;
using System.Collections.Generic;

namespace ConsoleApp57
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "DefaultEndpointsProtocol=https;AccountName=0427bowman;AccountKey=xxxxxx;EndpointSuffix=core.windows.net";
            string folder_main = "test1";
            List<string> subs3 = new List<string>();
            BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
            string containerName = "incoming";
            BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);
            var blobs = containerClient.GetBlobs(prefix: "test1");

            //Below code can get the path.
            foreach (var blob in blobs)
            {
                Console.WriteLine("---");
                Console.WriteLine(blob.Name);
                Console.WriteLine("---");
                string[] sub_names = blob.Name.Split('/');
                Console.WriteLine(sub_names.Length);
                //split the file name from the path.
                if (sub_names.Length > 1 && !subs3.Contains(sub_names[sub_names.Length-1]))
                {
                    subs3.Add(sub_names[sub_names.Length-1]);
                }
            }
            //Below code can get the file name.
            foreach (var sub3 in subs3)
            {
                Console.WriteLine("----");
                Console.WriteLine(sub3);
                Console.WriteLine("----");
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)