简体   繁体   中英

AWS lambda .net core 2.1 list files in S3 bucket

As the title indicates, I'm wanting to list files (keys) in an S3 bucket in my lambda function.

I have the following so far:

public static async Task < bool > ListObjectsInBucket(string S3_ACCESS_KEY_ID, string S3_SECRET_ACCESS_KEY, string S3_REGION, string S3_BUCKET, string GC_ClientID) {

 try {
  // Create a client
  var regionIdentifier = RegionEndpoint.GetBySystemName(S3_REGION);
  AmazonS3Client client = new AmazonS3Client(S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY, regionIdentifier);

  // List all objects
  ListObjectsRequest listRequest = new ListObjectsRequest {
   BucketName = S3_BUCKET + "/" + GC_ClientID + "/news-articles",
  };

  ListObjectsResponse listResponse;
  do {
   // Get a list of objects
   listResponse = await client.ListObjectsAsync(listRequest);
   foreach(S3Object obj in listResponse.S3Objects) {
    Console.WriteLine("Object - " + obj.Key);
    Console.WriteLine(" Size - " + obj.Size);
    Console.WriteLine(" LastModified - " + obj.LastModified);
    Console.WriteLine(" Storage class - " + obj.StorageClass);
   }

   // Set the marker property
   listRequest.Marker = listResponse.NextMarker;
  } while (listResponse.IsTruncated);

  return true;

 } catch (Exception ex) {
  Console.WriteLine("Exception:" + ex.Message);
  return false;
 }
}

and the following calls it:

public string FunctionHandler(ILambdaContext context) {

 var checkFile = ListObjectsInBucket(S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY, S3_REGION, S3_BUCKET, GC_ClientID);

 return "Complete: " + checkFile;

}

I'm getting the following error:

"Complete: System.Runtime.CompilerServices.AsyncTaskMethodBuilder 1+AsyncStateMachineBox 1[System.Boolean,ExportArticles.Function+d__3]"

Can anyone help???

Since your list call is async you need to make your function handler async. Right now you are calling your async list method from your function handler and then immediately returning before the async method completes. Your function handler should be something like

public async Task<string> FunctionHandler(ILambdaContext context) {

 var checkFile = await ListObjectsInBucket(S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY, S3_REGION, S3_BUCKET, GC_ClientID);

 return "Complete: " + checkFile;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM