2010-05-09 52 views
6

我目前使用下面的代碼來檢索並解壓縮從亞馬遜C#字符串數據:C#代碼gzip和上傳串到Amazon S3

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, 0, buffer.Length); 

      PutObjectRequest request = new PutObjectRequest(); 
      request.InputStream = ms; 
      request.Key = awsPath; 
      request.BucketName = AWSS3BuckenName; 

      using (S3Response putResponse = client.PutObject(request)) 
      { 
       //process response 
      } 
     } 
    } 
} 

我得到的例外是:

無法訪問已關閉的流。

我在做什麼錯?

編輯:

例外是使用上的右括號存在的(GZipStream拉鍊

堆棧跟蹤:

在 System.IO.MemoryStream.Write(字節[] 緩衝區,Int32偏移量,Int32計數)
at System.I O.Compression.DeflateStream.Dispose(布爾 處置)在 System.IO.Stream.Close()在 System.IO.Compression.GZipStream.Dispose(布爾 處置)在 System.IO.Stream.Close()

+0

發生異常的地方在哪裏?你可以添加一個完整的堆棧跟蹤? – dtb 2010-05-09 17:19:58

+0

謝謝。另外我發佈了異常詳細信息 – BigJoe714 2010-05-09 17:23:28

回答

11

你需要刷新和關閉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, 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 
} 

它可能還可以使用GZipStream作爲輸入如果你首先用數據填充MemoryStream,但我還沒有嘗試過。

+0

謝謝!有效 – BigJoe714 2010-05-09 19:52:01