C # code for gzip and upload string to Amazon S3

I am currently using the following code to extract and extract string data from Amazon C #:

GetObjectRequest getObjectRequest = new GetObjectRequest().WithBucketName(bucketName).WithKey(key); using (S3Response getObjectResponse = client.GetObject(getObjectRequest)) { using (Stream s = getObjectResponse.ResponseStream) { using (GZipStream gzipStream = new GZipStream(s, CompressionMode.Decompress)) { StreamReader Reader = new StreamReader(gzipStream, Encoding.Default); string Html = Reader.ReadToEnd(); parseFile(Html); } } } 

I want to cancel this code so that I can compress and unload string data on S3 without writing to disk. I tried the following but get an exception:

 using (AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(AWSAccessKeyID, AWSSecretAccessKeyID)) { string awsPath = AWSS3PrefixPath + "/" + keyName+ ".htm.gz"; byte[] buffer = Encoding.UTF8.GetBytes(content); using (MemoryStream ms = new MemoryStream()) { using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress)) { zip.Write(buffer, 0, buffer.Length); PutObjectRequest request = new PutObjectRequest(); request.InputStream = ms; request.Key = awsPath; request.BucketName = AWSS3BuckenName; using (S3Response putResponse = client.PutObject(request)) { //process response } } } } 

The exception that I get is:

Unable to access closed stream.

What am I doing wrong?

EDIT:

An exception occurs on the closing bracket using (GZipStream zip

Stack trace:

in System.IO.MemoryStream.Write (byte [] buffer, Int32 offset, Int32 count)
at System.IO.Compression.DeflateStream.Dispose (Boolean disposition) at System.IO.Stream.Close () at System.IO.Compression.GZipStream.Dispose (Boolean disposition) at System.IO.Stream.Close ()

+6
c # amazon-s3 amazon-web-services
source share
1 answer

You need to clear and close the GZipStream and reset the Position of MemoryStream to 0 before using it as input to the request:

 MemoryStream ms = new MemoryStream(); using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true)) { byte[] buffer = Encoding.UTF8.GetBytes(content); zip.Write(buffer, 0, buffer.Length); zip.Flush(); } ms.Position = 0; PutObjectRequest request = new PutObjectRequest(); request.InputStream = ms; request.Key = AWSS3PrefixPath + "/" + keyName+ ".htm.gz"; request.BucketName = AWSS3BuckenName; using (AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client( AWSAccessKeyID, AWSSecretAccessKeyID)) using (S3Response putResponse = client.PutObject(request)) { //process response } 

It is also possible to use GZipStream as input if you first populate a MemoryStream with data, but I have not tried this yet.

+11
source share

All Articles