如何使用SevenZip压缩/解压缩字符串 - 7Zip

时间:2014-09-14 15:31:04

标签: c# 7zip sevenzipsharp text-compression

文档很差,所以我很难做到这一点

我添加了dll文件和正确的引用

最后它压缩字符串但在解压缩时出错

你能告诉我错误在哪里吗?

    public static string SevenZip_CompressString(string text)
    {
        byte[] compressedData = null;

        SevenZipCompressor compressor = new SevenZipCompressor();
        compressor.CompressionMethod = CompressionMethod.Ppmd;
        compressor.CompressionLevel = SevenZip.CompressionLevel.Ultra;
        compressor.ScanOnlyWritable = true;
        compressor.DefaultItemName = "T";

        using (MemoryStream msin = new MemoryStream(Encoding.UTF8.GetBytes(text)))
        {
            using (MemoryStream msout = new MemoryStream())
            {
                compressor.CompressStream(msin, msout);

                compressedData = msout.ToArray();
            }
        }

        return System.Text.Encoding.UTF8.GetString(compressedData);
    }

下面解压缩

    public static string SevenZip_DE_CompressString(string compressedText)
    {
        byte[] uncompressedbuffer = null;

        using (MemoryStream compressedbuffer = new MemoryStream(Encoding.UTF8.GetBytes(compressedText)))
        {
            using (SevenZipExtractor extractor = new SevenZipExtractor(compressedbuffer))
            {
                using (MemoryStream msout = new MemoryStream())
                {
                    extractor.ExtractFile(0, msout);
                    uncompressedbuffer = msout.ToArray();
                }
            }
        }

        return Encoding.UTF8.GetString(uncompressedbuffer);
    }

此处出现错误消息

c#.net 4.5 WPF,

包\ SevenZipSharp.0.64 \ lib中\ SevenZipSharp.dll

enter image description here

1 个答案:

答案 0 :(得分:1)

这些都是错的:

System.Text.Encoding.UTF8.GetString(compressedData)
Encoding.UTF8.GetBytes(compressedText)

压缩数据不是UTF-8。你不应该试着把它当成文本。始终将压缩数据存储为二进制,格式为byte[]。如果您需要通过纯文本通道(如电子邮件)传递它,请使用Base64编码。

从根本上说,改变你的想法。压缩不是函数string -> string。它是byte[] -> byte[]。将其视为string -> byte[]也是有效的。