我目前使用以下代码从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); } } }
我想反转这段代码,以便我可以压缩并将字符串数据上传到S3,而无需写入磁盘.我尝试了以下,但我得到一个例外:
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,buffer.Length); PutObjectRequest request = new PutObjectRequest(); request.InputStream = ms; request.Key = awsPath; request.BucketName = AWSS3BuckenName; using (S3Response putResponse = client.PutObject(request)) { //process response } } } }
我得到的例外是:
Cannot access a closed Stream.
我究竟做错了什么?
编辑:
在使用的结束括号(GZipStream zip)上发生异常
堆栈跟踪:
at
System.IO.MemoryStream.Write(Byte[]
buffer,Int32 offset,Int32 count)
at
System.IO.Compression.DeflateStream.Dispose(Boolean
disposing) at
System.IO.Stream.Close() at
System.IO.Compression.GZipStream.Dispose(Boolean
disposing) at
System.IO.Stream.Close()
解决方法
在将其用作请求的输入之前,您需要刷新并关闭GZipStream并将MemoryStream的位置重置为0:
MemoryStream ms = new MemoryStream(); using (GZipStream zip = new GZipStream(ms,CompressionMode.Compress,true)) { byte[] buffer = Encoding.UTF8.GetBytes(content); zip.Write(buffer,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 }
如果您首先使用数据填充MemoryStream,也可以使用GZipStream作为输入,但我还没有尝试过.