为什么压缩然后是不同长度的未压缩流

Chr*_*sAU 2 .net c# compression 7zip sevenzipsharp

我正在使用SevenZipSharp库来压缩然后解压缩包含简单序列化对象的MemoryStream.但是,压缩和解压缩的流具有不同的长度.

从下面的代码运行我得到

输入长度:174输出长度:338

(包含SevenZipSharp dll作为参考,7z.dll包含在项目输出中)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace DataTransmission {
class Program {
    static void Main(string[] args)
    {

        SevenZip.SevenZipCompressor compressor = new SevenZip.SevenZipCompressor();
        //compressor.CompressionMethod = SevenZip.CompressionMethod.Lzma2;
        //compressor.CompressionLevel = SevenZip.CompressionLevel.Normal;

        MemoryStream inputStream = new MemoryStream();

        Person me = new Person("John", "Smith");
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(inputStream, me);

        Int32 inputStreamLength = (Int32)inputStream.Length;

        MemoryStream outputStream = new MemoryStream();

        compressor.CompressStream(inputStream, outputStream);
        SevenZip.SevenZipExtractor decompressor = new SevenZip.SevenZipExtractor(outputStream);
        decompressor.ExtractFile(0, outputStream);
        Int32 outputStreamLength = (Int32)outputStream.Length;


        Console.WriteLine("Input length: {0}", inputStreamLength);
        Console.WriteLine("Output length: {0}", outputStreamLength);

        Console.ReadLine();
    }
}

[Serializable]
public class Person {
    public string firstName;
    public string lastName;

    public Person(string fname, string lname) {
        firstName = fname;
        lastName = lname;
    }
}

}
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮我解释为什么会这样吗?

谢谢,

Jon*_*eet 5

outputStream尽管已经包含了数据,但你已经解压缩了.您应该使用new MemoryStream作为输出.

(事实上,这是因为解压缩器阅读是件很奇怪 outputStream,也写 outputStream.糟糕的主意.使用两个不同的流.)

您还应该在写完每个流之后以及其他想要阅读它的内容之前回放每个流,例如

inputStream.Position = 0;
Run Code Online (Sandbox Code Playgroud)

在这种情况下,SevenZipLib可能会为您执行此操作,但一般情况下,如果您希望从流的开头执行某些操作,则应该适当地重置它.


我刚刚对您的代码进行了以下更改,此时输入和输出的长度相同:

MemoryStream targetStream = new MemoryStream();
decompressor.ExtractFile(0, targetStream);
Int32 outputStreamLength = (Int32)targetStream.Length;
Run Code Online (Sandbox Code Playgroud)

正如我所说,你也应该做出适当的其他改变.