SharpZipLib压缩文件,解压zip文件时出现:文件末端错误
解决:在ZipOutputStream.Close()之后,它的输出流数据才完整,因此在ZipOutputStream.Close()之后再来获取数据。
相关参考:https://blog.csdn.net/lz20120808/article/details/94020004
SharpZipLib源码 https://github.com/icsharpcode/SharpZipLib
ZipOutputStream https://github.com/icsharpcode/SharpZipLib/blob/master/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs
private byte[] GetZipBytes(List<YamlFile> yamlFiles)
{
byte[] buffer;
using (MemoryStream memoryStream = new MemoryStream())//MemoryStream为内存流
{
// 文件流、内存流都可以,压缩后的内容会写入到这个流中。
using (ZipOutputStream zipStream = new ZipOutputStream(memoryStream))
{
zipStream.SetLevel(9);
foreach (var yamlFile in yamlFiles)
{
byte[] bytes = Encoding.UTF8.GetBytes(yamlFile.Content);
ZipEntry zipEntry = new ZipEntry(yamlFile.FileName);
zipEntry.DateTime = DateTime.Now;
zipEntry.Size = bytes.Length;
zipEntry.IsUnicodeText = true;
zipStream.PutNextEntry(zipEntry);
zipStream.Write(bytes, 0, bytes.Length);
zipStream.CloseEntry();
}
// 使用流操作时一定要设置IsStreamOwner为false。否则很容易发生在文件流关闭后的异常。
zipStream.IsStreamOwner = false;
zipStream.Finish();
zipStream.Close();
}
// 注意:应当在 ZipOutputStream.Close()之后再获取buffer,否则如果在ZipOutputStream.Close()之前获取,则解压zip文件将会出现“文件末端错误”
buffer = memoryStream.ToArray();
memoryStream.Close();
}
return buffer;
}
原因分析:调用zipStream.Close()将会调用ZipStream.Finish() ,Finish说明:Finishes the stream. This will write the central directory at the end of the zip file and flush the stream.它将会写入部分数据,这样zip才是完整的。
网友评论