我需要压缩和解压缩字符串
这是代码:
public static byte[] ZipStr(String str)
{
using (MemoryStream output = new MemoryStream())
using (DeflateStream gzip = new DeflateStream(output, CompressionMode.Compress))
using (StreamWriter writer = new StreamWriter(gzip))
{
writer.Write(str);
return output.ToArray();
}
}
和
public static string UnZipStr(byte[] input)
{
using (MemoryStream inputStream = new MemoryStream(input))
using (DeflateStream gzip = new DeflateStream(inputStream, CompressionMode.Decompress))
using (StreamReader reader = new StreamReader(gzip))
{
reader.ReadToEnd();
return System.Text.Encoding.UTF8.GetString(inputStream.ToArray());
}
}
似乎UnZipStr方法中存在错误。有人能帮助我吗?
答案 0 :(得分:29)
有两个不同的问题。首先,在ZipStr
中,您需要刷新或关闭StreamWriter
并关闭DeflateStream
,然后才能阅读MemoryStream
。
其次,在UnZipStr
中,您正在构建inputStream
中压缩字节的结果字符串。您应该返回reader.ReadToEnd()
的结果。
在StreamWriter
和StreamReader
构造函数中指定字符串编码也是一个好主意。
请尝试使用以下代码:
public static byte[] ZipStr(String str)
{
using (MemoryStream output = new MemoryStream())
{
using (DeflateStream gzip =
new DeflateStream(output, CompressionMode.Compress))
{
using (StreamWriter writer =
new StreamWriter(gzip, System.Text.Encoding.UTF8))
{
writer.Write(str);
}
}
return output.ToArray();
}
}
public static string UnZipStr(byte[] input)
{
using (MemoryStream inputStream = new MemoryStream(input))
{
using (DeflateStream gzip =
new DeflateStream(inputStream, CompressionMode.Decompress))
{
using (StreamReader reader =
new StreamReader(gzip, System.Text.Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
}
}