C# 读取压缩文件方式及乱码处理

目前主流的压缩文件操作类,除了C#原生的。还有

1. ZIP-DotNetZip

网址:http://dotnetzip.codeplex.com/ 

2 7Zip-SevenZipSharp

网址:http://sevenzipsharp.codeplex.com/ 

支持的格式比上面多,如:7Zip,RAR,ZIP,Gzip,Cab,LZH等等。注意,除了引用这个组件之外,还需要加7z.dll文件拷贝到bin目录中,因为SevenZipSharp是对7z.dll的一个封装。

3 综合-SharpCompress 

网址:http://sharpcompress.codeplex.com/

支持的格式更多,如RAR,ZIP,Tar,7Zip等等。这个开源项目好像是去年才开始的,在其他几个开源的项目基础上发展而来,也包括了DotNetZipNunrar项目。当然对RAR也只是解压.

中文支持问题:

推荐:SevenZipSharp

1.速度快。

2.支持中文,不会有乱码。

3.接口类定义明确,实用。

SharpCompress 对中文支持不好。

原因:在使用BinaryReader时,SharpCompress 会读取文件的Header的编码,没有时 默认使用UTF-8的读取。造成乱码文件。

但同时也有解决方案。(不建议修改SharpCompress的源码)。

只需要在调用前 修改下 SharpCompress的编码方式.

public static void Reader(string filePath)
        {
            using (Stream stream = File.OpenRead(filePath))
            {
                //设置编码为 Default
                SharpCompress.Common.ArchiveEncoding.Default = System.Text.Encoding.Default;
                var reader = ReaderFactory.Open(stream);

                while (reader.MoveToNextEntry())
                {
                    Console.WriteLine("测试");
                }
            }
        }

 但相比较而言,性能还是没有SevenZipSharp好,所以还是推荐SevenZipSharp。

后记:SevenZipSharp的怪现象

使用framework 4.5 编译时  会报can't load  7z.dll  failed to load library。

将项目 改为4.0 后 再运行OK了,再改为 4.5  又不报错了。

内部运行代码 NativeMethods.cs

[DllImport("kernel32.dll", BestFitMapping = false, ThrowOnUnmappableChar = true)]
        public static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string fileName);

推荐文章:http://www.cnblogs.com/asxinyu/archive/2013/03/05/2943696.html

原文地址:https://www.cnblogs.com/shikyoh/p/5018914.html