Ahmed Elshorbagy
Ahmed Elshorbagy

Reputation: 362

Get files names in sub-directories in a directory in AWS3 by C#

I'm trying to get files names in sub-directories in a directory in AWS Bucket. I can get the sub-directories name but I don't know how to list the files under the sub-directory.

The following code get the sub-directories name but the files names in those sub-directories

var accessKey = "my key";
var secretKey = "my secret key";

IAmazonS3 client = new AmazonS3Client(accessKey, secretKey, RegionEndpoint.USEast1);
S3DirectoryInfo dir = new S3DirectoryInfo(client, "mybucketname", "foldername");

foreach (IS3FileSystemInfo file in dir.GetFileSystemInfos())
{
  filename= file.Name;
}

Thanks

Upvotes: 0

Views: 3755

Answers (1)

SilentTremor
SilentTremor

Reputation: 4902

I'm using nuget packages (.net core, but syntax should be similar because I migrated to .net core short time ago)

  • AWSSDK.Core
  • AWSSDK.S3

with

 public async Task<List<string>> ListS3ObjectsNames(string bucket, string prefix)
        {
            var awsAccessKey = "dasdasda";
            var awsSecretKey = "asdadasdsecret";
            var region = Amazon.RegionEndpoint.USEast1;
            using (var client = new AmazonS3Client(awsAccessKey, awsSecretKey, region))
            {
                var response = await client.ListObjectsAsync(bucket, prefix);
                return response.S3Objects.Count == 0 ? new List<string>() : response.S3Objects.Select(x => x.Key).ToList();
            }
        }

In asp.net 4.5 to 4.6 if I remember correct method is ListObjects and is non async.

Upvotes: 3

Related Questions