C# code to GZip and upload a string to Amazon S3
- by BigJoe714
Hello. I currently use the following code to retrieve and decompress 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 reverse this code so that I can compress and upload string data to S3 without being written to disk. I tried the following, but I am getting 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 I am getting is:
Cannot access a closed Stream.
What am I doing wrong?