Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Process file on S3 event through AWS lambda using C#

I am looking for C# code blocks to read file from S3 on PUT event and upload the file to another bucket. I am fairly new to C# and see most of the blogs are either written for python and java. Any help will be highly appreciated.

Thanks,

like image 578
Shailendra Sharma Avatar asked Sep 18 '25 14:09

Shailendra Sharma


1 Answers

I know it's too late but maybe this will help someone else. You need to add Amazon.Lambda.S3Events Nuget package. See code, this is how your Lambda Function should look like:

using System;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
using Amazon.Lambda.S3Events;
using Amazon.S3;
using Amazon.S3.Model;

public async Task<string> FunctionHandler(S3Event evnt, ILambdaContext context)
{
    var s3Event = evnt.Records?[0].S3;
    if(s3Event == null)
    {
        return null;
    }

    try
    {
        var destinationBucketName = "your_bucket_to_upload";
        var destinationKey= "folder/subfolder/fileName.txt";

        var s3 = new AmazonS3Client();
        var request = new CopyObjectRequest
        {
            SourceBucket = s3Event.Bucket.Name,
            SourceKey = s3Event.Object.Key,
            DestinationBucket = destinationBucketName,
            DestinationKey = destinationKey
        };
        
        var response = await s3.CopyObjectAsync(request);
        return response.HttpStatusCode.ToString();
    }
    catch(Exception e)
    {
        context.Logger.LogLine($"Error getting object {s3Event.Object.Key} from bucket {s3Event.Bucket.Name}. Make sure they exist and your bucket is in the same region as this function.");
        context.Logger.LogLine(e.Message);
        context.Logger.LogLine(e.StackTrace);
        throw;
    }
}

You can find AWS Toolkit for Visual Studio here: https://docs.aws.amazon.com/lambda/latest/dg/csharp-package-toolkit.html

like image 124
Foggy Avatar answered Sep 21 '25 04:09

Foggy