使用S3网址从S3存储桶读取文本文件内容

时间:2019-04-30 19:18:48

标签: .net amazon-web-services amazon-s3 aws-lambda core

需要读取在aws S3存储桶中上载的文本文件的内容。 我有位于S3存储桶中的文件的url。有人可以帮助我使用S3网址读取文本文件内容。

我知道我们可以使用ResponseStream读取数据,但想使用Url / Path读取数据。需要使用.net核心创建AWS lambda。下面的代码重点介绍了如何使用responsestream读取它

using (GetObjectResponse response = await _client.GetObjectAsync(requestGet))
using (Stream responseStream = response.ResponseStream)
using (StreamReader reader = new StreamReader(responseStream))

1 个答案:

答案 0 :(得分:1)

AWS .Net SDK是您的问题的答案:

-通过在请求中提供存储区名称和对象键来执行getObject方法。

-执行GetObjectResponse方法之一来处理流。

以下是来自AWS link的相同示例:

using Amazon.S3;
using Amazon.S3.Model;
using System;
using System.IO;
using System.Threading.Tasks;

namespace Amazon.DocSamples.S3
{
    class GetObjectTest
    {
        private const string bucketName = "*** bucket name ***";
        private const string keyName = "*** object key ***";
        // Specify your bucket region (an example region is shown).
        private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USWest2;
        private static IAmazonS3 client;

        public static void Main()
        {
            client = new AmazonS3Client(bucketRegion);
            ReadObjectDataAsync().Wait();
        }

        static async Task ReadObjectDataAsync()
        {
            string responseBody = "";
            try
            {
                GetObjectRequest request = new GetObjectRequest
                {
                    BucketName = bucketName,
                    Key = keyName
                };
                using (GetObjectResponse response = await client.GetObjectAsync(request))
                using (Stream responseStream = response.ResponseStream)
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    string title = response.Metadata["x-amz-meta-title"]; // Assume you have "title" as medata added to the object.
                    string contentType = response.Headers["Content-Type"];
                    Console.WriteLine("Object metadata, Title: {0}", title);
                    Console.WriteLine("Content type: {0}", contentType);

                    responseBody = reader.ReadToEnd(); // Now you process the response body.
                }
            }
            catch (AmazonS3Exception e)
            {
                Console.WriteLine("Error encountered ***. Message:'{0}' when writing an object", e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
            }
        }
    }
}