C# gzipstream解压更像是抑郁症
为什么我不能让这段代码在这里工作?我想在之前压缩的字节数组上调用它......无论如何,它只是返回一个空字符串......
public static string FromGZipToString( this byte[] source )
{
using( MemoryStream stream = new MemoryStream( ) )
{
stream.Write( source, 0, source.Length );
using (var gzipstream = new GZipStream(stream, CompressionMode.Decompress))
using (var reader = new StreamReader(gzipstream))
{
return reader.ReadToEnd( );
}
}
}
顺便说一句,这是压缩代码......
public static byte[] ToGZip( this string source )
{
using( var stream = new MemoryStream( ) )
using( var compressor = new GZipStream( stream, CompressionMode.Compress ) )
{
var bytes = System.Text.UTF8Encoding.UTF8.GetBytes( source );
compressor.Write( bytes, 0, bytes.Length );
return stream.ToArray( );
}
}
why can't I get this code here to work? I want to call this on a byte array that was previously compressed....anyway, it just returns an empty string...
public static string FromGZipToString( this byte[] source )
{
using( MemoryStream stream = new MemoryStream( ) )
{
stream.Write( source, 0, source.Length );
using (var gzipstream = new GZipStream(stream, CompressionMode.Decompress))
using (var reader = new StreamReader(gzipstream))
{
return reader.ReadToEnd( );
}
}
}
here is the compress code by the way....
public static byte[] ToGZip( this string source )
{
using( var stream = new MemoryStream( ) )
using( var compressor = new GZipStream( stream, CompressionMode.Compress ) )
{
var bytes = System.Text.UTF8Encoding.UTF8.GetBytes( source );
compressor.Write( bytes, 0, bytes.Length );
return stream.ToArray( );
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的压缩程序有问题。在压缩机关闭(或处置)之前,它不应该从流中读取,从而允许压缩机完成将所有字节写入流。
看看我对此问题的回答:压缩和解压缩源数据给出的结果与源数据不同
Your compression routine is faulty. It shouldn't be reading from stream until the compressor has been closed (or disposed), allowing the compressor to finish writing all bytes to the steam.
Check out my answer to this question: compressing and decompressing source data gives result different than source data