压缩和解压缩字符串放气 [英] zip and unzip string with Deflate

查看:173
本文介绍了压缩和解压缩字符串放气的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hi I need to zip and unzip string

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

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方法错误。有人可以帮我吗?

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

推荐答案

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

There are two separate problems. First of all, in ZipStr you need to flush or close the StreamWriter and close the DeflateStream before reading from the MemoryStream.

其次, UnZipStr ,你构建从COM pressed字节你的结果字符串的InputStream 。你应该返回的结果 reader.ReadToEnd()代替。

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.

这也将是指定的的StreamWriter 的StreamReader 构造函数的字符串编码是个好主意。

It would also be a good idea to specify the string encoding in the StreamWriter and StreamReader constructors.

请尝试以下code来代替:

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

这篇关于压缩和解压缩字符串放气的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆