gpt4 book ai didi

c# - 为什么压缩流和未压缩流的长度不同

转载 作者:行者123 更新时间:2023-12-03 03:00:20 24 4
gpt4 key购买 nike

我正在使用 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;
}
}

}

谁能帮我解释一下为什么会这样?

谢谢

最佳答案

尽管已经包含数据,但您已解压缩到 outputStream 中。您应该使用 MemoryStream 作为输出。

(事实上,这很奇怪,因为解压缩器正在从 outputStream 读取,同时也将写入 outputStream .坏主意。使用两个不同的流。)

您还应该在写入每个流之后以及其他东西想要读取它之前倒回每个流,例如与

inputStream.Position = 0;

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

<小时/>

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

MemoryStream targetStream = new MemoryStream();
decompressor.ExtractFile(0, targetStream);
Int32 outputStreamLength = (Int32)targetStream.Length;

正如我所说,您也应该进行适当的其他更改。

关于c# - 为什么压缩流和未压缩流的长度不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5974458/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com