C# Zip解压缩,规避 [content_types].xml 文件

使用 System.IO.Packaging.Package 进行压缩和解压时,会自动生成 [content_types].xml 文件。

The Structure of the [Content_types].xml File - Visual Studio | Microsoft Docs

压缩时生成这个其实无所谓,但解压文件时,也必须有这个文件的存在,否则不能解压。这就不能忍了,毕竟不是所有的 Zip 压缩包都会带这个文件的。

怎么解?

System.IO.Compression.ZipFile

最简单的方式,就是使用 System.IO.Compression.ZipFile 这个类,使用方式如下(示例):


        /// <summary>
        /// 解压文件,这个方法不需要压缩包中有 [Content_Types].xml 文件。
        /// </summary>
        public static IEnumerable<string> DecompressFileCompatibly(string target, string outPath)
        {
            ZipArchive zipArchive = ZipFile.Open(target, ZipArchiveMode.Read);

            // 获取所有文件(相对路径)
            var files = zipArchive.Entries.Select(e => e.FullName).ToList();

            // 解压文件 (要求 outPath 不能存在,必须是全新的)
            zipArchive.ExtractToDirectory(outPath);

            // 返回的文件列表中,不需要有 [Content_Types].xml 文件。
            files.Remove("[Content_Types].xml");

            // 最终解压出来的所有文件
            var fileList = files.Where(f =>
            {
                var file = Path.Combine(outPath, f);
                return File.Exists(file); // 过滤文件夹
            }).Select(f => Path.Combine(outPath, f)).ToList();

            return fileList;
        }

其它方式

也可以使用第三方库处理这个问题,如:

SharpZipLib | #ziplib is a Zip, GZip, Tar and BZip2 library written entirely in C# for the .NET platform.
DotNetZip Library - CodePlex Archive

参考资料:
how to avoid [Content_Types].xml in .net's ZipPackage class - Stack Overflow

猜你喜欢

转载自www.cnblogs.com/jasongrass/p/10579477.html