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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2118904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:40:05  来源:igfitidea点击:

zip and unzip string with Deflate

c#.netdeflatestream

提问by Mikhail

I need to zip and unzip string

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

Here is code:

这是代码:

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

and

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

It seems that there is error in UnZipStr method. Can somebody help me?

UnZipStr 方法似乎有错误。有人可以帮助我吗?

采纳答案by Phil Ross

There are two separate problems. First of all, in ZipStryou need to flush or close the StreamWriterand close the DeflateStreambefore reading from the MemoryStream.

有两个不同的问题。首先,在ZipStr你需要刷新或关闭StreamWriter和关闭DeflateStream从阅读之前MemoryStream

Secondly, in UnZipStr, you're constructing your result string from the compressed bytes in inputStream. You should be returning the result of reader.ReadToEnd()instead.

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

It would also be a good idea to specify the string encoding in the StreamWriterand StreamReaderconstructors.

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

Try the following code instead:

请尝试以下代码:

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