0

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

我添加了 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

在此处输入图像描述

4

1 回答 1

2

这些是错误的:

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

压缩数据不是 UTF-8。而且您不应该尝试将其视为文本。始终以二进制形式存储压缩数据,作为byte[]. 如果您需要通过纯文本通道(例如电子邮件)传递它,请使用 Base64 编码。

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

于 2014-09-14T17:05:16.593 回答