使用Deflate压缩和解压缩字符串

时间:2010-01-22 16:55:37

标签: c# .net deflatestream

我需要压缩和解压缩字符串

这是代码:

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方法中存在错误。有人能帮助我吗?

1 个答案:

答案 0 :(得分:29)

有两个不同的问题。首先,在ZipStr中,您需要刷新或关闭StreamWriter并关闭DeflateStream,然后才能阅读MemoryStream

其次,在UnZipStr中,您正在构建inputStream中压缩字节的结果字符串。您应该返回reader.ReadToEnd()的结果。

StreamWriterStreamReader构造函数中指定字符串编码也是一个好主意。

请尝试使用以下代码:

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();
            }
        }
    }
}