我试图使用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);
}
}
}发布于 2018-02-01 13:16:11
尝试查看是否可以使用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);
}
}https://stackoverflow.com/questions/48563378
复制相似问题