c# - 如何使用 C# 通过 AWS lambda 处理 S3 事件上的文件

标签 c# amazon-web-services amazon-s3 aws-lambda

我正在寻找 C# 代码块以在 PUT 事件上从 S3 读取文件并将文件上传到另一个存储桶。我对 C# 相当陌生,看到大多数博客都是为 python 和 java 编写的。任何帮助将不胜感激。

谢谢,

最佳答案

我知道为时已晚,但也许这会对其他人有所帮助。
您需要添加 Amazon.Lambda.S3Events Nuget 包。查看代码,这是您的 Lambda 函数的样子:

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;
        }
    }
您可以在此处找到适用于 Visual Studio 的 AWS Toolkit:
https://docs.aws.amazon.com/lambda/latest/dg/csharp-package-toolkit.html

关于c# - 如何使用 C# 通过 AWS lambda 处理 S3 事件上的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59580592/

相关文章:

python-3.x - 使用 chalice 部署时 Lambda 超时配置重置为 1

c# - 创建泛型列表

c# - P/invoke 函数采用指向结构的指针

c# - BeginLifetimeScope/DbContext 的 Autofac 和内存泄漏已被处理/C# asp.net

python - AWS cloudformation堆栈状态

http - Amazon S3 CORS header 仅在 OPTIONS(预检)期间显示,而不在 GET 请求期间显示

c# - WinRT 应用程序和区域设置。根据用户的区域设置格式化日期和数字的正确方法?

swift - 部署自定义运行时 lambda 时 sam 包太大

amazon-s3 - Amazon S3 中的对象 ID 有哪些限制?

ios - 是否无法使用 AWS CloudFront 在 S3 上下载我的私有(private)镜像?