前言:网上有很多关于SharpZip如何创建压缩包以及如何解压的博文,向压缩包中添加文件很多人用Zip.Add()方法,但是这种方法,有很大的弊端:
1、会把该文件所在的目录也添加进去。如果用户需要这样的效果,那这方法自然是极好的,但是我们有时候我们还需要,
向压缩包的根目录添加文件或者向压缩包中指定的目录添加文件。
2.有人说这种添加方法会覆盖压缩包中的文件,解决办法是用一个类实现了Zip.Add()方法的一个接口IStaticDataSource,然后调用Zip.Add(IStaticDataSource,string)方法,我也试着这样弄了一下,
但是发现没运行了以后代码文件损坏,不仅无法直接预览压缩包中的其他文件,并且添加的文件也不显示,但是解压了以后却又是好的,真是让人头疼。后来还是弃用了这种方法。
向压缩包的根目录添加文件或者向压缩包中指定的目录添加文件两种方法在网上的资源是极少的,折腾了几天,终于解决了,贴下代码。
C# Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
/// /// 向压缩包的根目录添加文件 /// /// 需要压缩的文件(绝对路径) /// 压缩包路径(绝对路径) public static bool AddFileToRoot( string pathToZip, string [] FileToZip) { try { using (ZipFile zip = new ZipFile(pathToZip)) { zip.BeginUpdate(); foreach ( string file in FileToZip) { zip.Add(file, Path.GetFileName(file)); } zip.CommitUpdate(); } return true ; } catch (Exception ex) { throw ex; } } |
C# Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
/// /// 向压缩包中的指定文件夹添加数据,如果文件夹不存在,则创建该文件夹并添加 /// /// 压缩包路径 /// 要添加的文件路径 /// 压缩包中的路径 /// public static bool AddFileToDirectory( string pathToZip, string [] FileToZip, string directory) { try { using (ZipFile zip = new ZipFile(pathToZip)) { //添加文件夹 AddDirectoryToZip(pathToZip, directory); //像文件夹中添加数据 zip.BeginUpdate(); foreach ( string file in FileToZip) { string fileName = Path.GetFileName(file); zip.Add(file, directory + "\\" + fileName); } zip.CommitUpdate(); } return true ; } catch (Exception ex) { throw ex; } } |