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

5
需要列出“Test”文件夹中一个特定目录中的所有文件,但不包括“Test2”。我尝试使用“test”作为前缀,但它会返回两个文件夹。
容器:“myContainer”
TEST:
- file1.jpg - file2.jpg
TEST2:
- file1.jpg
我尝试了以下方法,但它返回了两个文件夹以及输出路径:
- Test/file1.jpg - Test/file2.jpg - Test2/file1.jpg
我能否仅返回文件而不是路径?
  • file1.jpg

  • file2.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);
         }
    

嗨,你测试了我发布的代码吗?有更新吗? - Cindy Pau
2个回答

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("----");
            }
        }
    }
}

2

您可以简单地将prefix替换为空字符串以获取文件名。例如:

string fileName = blob.Name;
string prefix = "test/";
if (fileName.StartsWith(prefix))
{
    fileName = fileName.Replace(prefix, "");
}
result.FileName = fileName;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接