美文网首页
SharpZipLib压缩文件,解压zip文件时出现:文件末端错

SharpZipLib压缩文件,解压zip文件时出现:文件末端错

作者: ljt001 | 来源:发表于2021-07-09 12:03 被阅读0次

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才是完整的。

相关文章

  • SharpZipLib压缩文件,解压zip文件时出现:文件末端错

    SharpZipLib压缩文件,解压zip文件时出现:文件末端错误解决:在ZipOutputStream.Clos...

  • 文件处理-Linux

    1 .zip 文件 zip压缩文件 .zip文件解压缩 2 .gz 文件 gzip, gunzip, zcat -...

  • 解压缩文件

    1. zip linux中压缩文件 linux解压文件 2. tar linux中压缩文件tar -cvf /us...

  • ubantu 解压

    tar -zxvf ww.tar.gz 语法:unzip 〔选项〕 压缩文件名.zip -x 文件列表 解压缩文件...

  • linux压缩解压

    zip压缩解压 压缩文件 压缩目录 unzip解压缩 不重建文档的目录结构,把所有文件解压到同一目录下 将压缩文件...

  • 第6节 文件打包与解压缩

    文件打包与解压缩 0.0压缩文件类型: 文件后缀名 说明 *.zip zip 程序打包压缩的文件 *.rar ...

  • I/O

    获取文件信息 File类的常用方法 压缩文件 ZipOutputStream类的常用方法 解压缩ZIP文件 ZIP...

  • Linux文件操作

    Linux命令格式 zip格式的压缩 zip 压缩文件名 源文件 压缩文件zip -r 压缩文件名 源文件压缩文...

  • Linux基础04

    Linux压缩命令 .zip格式压缩 实例:压缩文件 zip 压缩文件名 原文件 实例:压缩文件夹 zip -r ...

  • 2020-01-09 数据压缩

    压缩文件包括zip,gzip,tar等等,创建压缩文件所需的计算资源远远多于解压缩。 有些压缩格式无需解压缩即可合...

网友评论

      本文标题:SharpZipLib压缩文件,解压zip文件时出现:文件末端错

      本文链接:https://www.haomeiwen.com/subject/ichtpltx.html