C#代码到GZip并将字符串上传到Amazon S3

前端之家收集整理的这篇文章主要介绍了C#代码到GZip并将字符串上传到Amazon S3前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我目前使用以下代码从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作为输入,但我还没有尝试过.

原文链接:https://www.f2er.com/csharp/244124.html

猜你在找的C#相关文章