Reputation: 125
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?
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);
}
Upvotes: 5
Views: 14414
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
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