我正在尝试使用SevenZipSharp来压缩和解压缩内存流。压缩工作正常,但减压不正常。我认为SevenZipSharp无法从流中找出存档类型。
SevenZipCompressor compress = new SevenZip.SevenZipCompressor();
compress.CompressionLevel = CompressionLevel.Normal;
compress.CompressionMethod = CompressionMethod.Lzma
using (MemoryStream memStream = new MemoryStream())
{
compress.CompressFiles(memStream, @"d:Temp1MyFile.bmp");
using (FileStream file = new FileStream(@"d:arch.7z", FileMode.Create, System.IO.FileAccess.Write))
{
memStream.CopyTo(file);
}
}
//works till here, file is created
Console.Read();
using (FileStream file = new FileStream(@"d:arch.7z", FileMode.Open, System.IO.FileAccess.Read))
{
using (MemoryStream memStream = new MemoryStream())
{
file.CopyTo(memStream);
//throws exception here on this line
using (var extractor = new SevenZipExtractor(memStream))
{
extractor.ExtractFiles(@"d:x", 0);
}
}
}
尝试查看是否可以使用 7Zip 客户端加载输出文件。我猜它会失败。
问题在于写入内存流。假设,您将 100 个字节写入流,它将位于位置 100。使用 CopyTo 时,将从当前位置复制流,而不是从流的开头复制流。
因此,您必须在读取/写入后将位置重置为 0,以允许下一个读取器读取所有数据。例如,在创建 7Zip 文件时:
using (MemoryStream memStream = new MemoryStream())
{
// Position starts at 0
compress.CompressFiles(memStream, @"d:Temp1MyFile.bmp");
// Position is now N
memStream.Position = 0; // <-- Reset the position to 0.
using (FileStream file = new FileStream(@"d:arch.7z", FileMode.Create, System.IO.FileAccess.Write))
{
// Will copy all data in the stream from current position till the end of the stream.
memStream.CopyTo(file);
}
}