Yzak
Yzak

Reputation: 125

Get files from a specific directory/folder in Azure Blob Storage inline with .NET SDK 12

I need to list all files from a specific directory from "Test" folder, EXCLUDING "Test2". I tried using "test" as prefix but it returns both folders.

Container: "myContainer"

TEST:

TEST2:

I tried the following but it returns both folders and path with output:

can I return the file ONLY instead of the path?

Upvotes: 5

Views: 14414

Answers (2)

suziki
suziki

Reputation: 14088

You can test the code below:

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

Upvotes: 6

Gaurav Mantri
Gaurav Mantri

Reputation: 136196

You can simply replace the prefix with an empty string to get the file name. Something like:

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

Upvotes: 2

Related Questions