dbo*_*oth 4 .net c# gzip c#-3.0 c#-4.0
我构建(基于CodeProject文章)一个包装类(C#)来使用a GZipStream来压缩a MemoryStream.它压缩很好但不会减压.我看了很多其他有相同问题的例子,我觉得我跟着说的是什么,但是当我解压缩时仍然没什么.这是压缩和解压缩方法:
public static byte[] Compress(byte[] bSource)
{
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream gzip = new GZipStream(ms, CompressionMode.Compress, true))
{
gzip.Write(bSource, 0, bSource.Length);
gzip.Close();
}
return ms.ToArray();
}
}
public static byte[] Decompress(byte[] bSource)
{
try
{
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream gzip = new GZipStream(ms, CompressionMode.Decompress, true))
{
gzip.Read(bSource, 0, bSource.Length);
gzip.Close();
}
return ms.ToArray();
}
}
catch (Exception ex)
{
throw new Exception("Error decompressing byte array", ex);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我如何使用它的一个例子:
string sCompressed = Convert.ToBase64String(CompressionHelper.Compress("Some Text"));
// Other Processes
byte[] bReturned = CompressionHelper.Decompress(Convert.FromBase64String(sCompressed));
// bReturned has no elements after this line is executed
Run Code Online (Sandbox Code Playgroud)
解压缩方法中存在一个错误.
代码不读取内容bSource.相反,它覆盖了从基于空内存流创建的空gzip读取的内容.
基本上你的代码版本在做什么:
//create empty memory
using (MemoryStream ms = new MemoryStream())
//create gzip stream over empty memory stream
using (GZipStream gzip = new GZipStream(ms, CompressionMode.Compress, true))
// write from empty stream to bSource
gzip.Write(bSource, 0, bSource.Length);
Run Code Online (Sandbox Code Playgroud)
修复程序可能如下所示:
public static byte[] Decompress(byte[] bSource)
{
using (var inStream = new MemoryStream(bSource))
using (var gzip = new GZipStream(inStream, CompressionMode.Decompress))
using (var outStream = new MemoryStream())
{
gzip.CopyTo(outStream);
return outStream.ToArray();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6139 次 |
| 最近记录: |