我正在尝试使用SevenZipSharp来压缩和解压缩内存流。压缩工作正常但解压缩却没有。我认为SevenZipSharp无法从流中找出存档类型。
SevenZipCompressor compress = new SevenZip.SevenZipCompressor();
compress.CompressionLevel = CompressionLevel.Normal;
compress.CompressionMethod = CompressionMethod.Lzma
using (MemoryStream memStream = new MemoryStream())
{
compress.CompressFiles(memStream, @"d:\Temp1\MyFile.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);
}
}
}
答案 0 :(得分:3)
尝试查看是否可以使用7Zip客户端加载输出文件。我猜它会失败。
问题在于写入内存流。比如说,您向流写入100个字节,它将位于位置100.当您使用CopyTo时,流将从当前位置复制,而不是从流的开头复制。
因此,您必须在读/写后将位置重置为0,以允许下一个读取器读取所有数据。例如,在创建7Zip文件时:
using (MemoryStream memStream = new MemoryStream())
{
// Position starts at 0
compress.CompressFiles(memStream, @"d:\Temp1\MyFile.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);
}
}