具体参见代码,就不再做其他相关说明了;这是用于上线产品中的源代码。
解压部分:
1 1 /// <summary> 2 2 /// 解压压缩包 3 3 /// </summary> 4 4 /// <param name="zipPath">压缩包的绝对路径</param> 5 5 /// <param name="dirPath">解压到的文件夹路径</param> 6 6 public static void UnZip(string zipPath, string dirPath) 7 7 { 8 8 // 判断ZIP文件是否存在 9 9 if (!System.IO.File.Exists(zipPath)) 1010 throw new FileNotFoundException(); 1111 1212 // 如果目标目录不存在就创建 1313 if (!Directory.Exists(dirPath)) 1414 Directory.CreateDirectory(dirPath); 1515 1616 //Shell的类型 1717 Type shellAppType = Type.GetTypeFromProgID("Shell.Application"); 1818 1919 //创建Shell对象 2020 object shell = Activator.CreateInstance(shellAppType); 2121 2222 // ZIP文件 2323 Shell32.Folder srcFile = (Shell32.Folder)shellAppType.InvokeMember("NameSpace", System.Reflection.BindingFlags.InvokeMethod, null, shell, new object[] { zipPath }); 2424 2525 // 解压到的目录 2626 Shell32.Folder destFolder = (Shell32.Folder)shellAppType.InvokeMember("NameSpace", System.Reflection.BindingFlags.InvokeMethod, null, shell, new object[] { dirPath }); 2727 2828 // 遍历ZIP文件 2929 foreach (var file in srcFile.Items()) 3030 { 3131 destFolder.CopyHere(file, 4 | 16); 3232 } 3333 }
压缩部分:
1 1 /// <summary> 2 2 /// 压缩文件夹内的文件到zip文件中 3 3 /// </summary> 4 4 /// <param name="dirPath">需要压缩的目录绝对路径</param> 5 5 /// <param name="zipPath">压缩后的绝对路径</param> 6 6 public static void ZipDir(string dirPath, string zipPath) 7 7 { 8 8 // 不存在地址则创建 9 9 if (!System.IO.File.Exists(zipPath)) 1010 using (System.IO.File.Create(zipPath)) { }; 1111 1212 //Shell的类型 1313 Type shellAppType = Type.GetTypeFromProgID("Shell.Application"); 1414 1515 //创建Shell对象 1616 object shell = Activator.CreateInstance(shellAppType); 1717 1818 // ZIP文件 1919 Shell32.Folder destFile = (Shell32.Folder)shellAppType.InvokeMember("NameSpace", System.Reflection.BindingFlags.InvokeMethod, null, shell, new object[] { zipPath }); 2020 2121 // 源文件夹 2222 Shell32.Folder srcFolder = (Shell32.Folder)shellAppType.InvokeMember("NameSpace", System.Reflection.BindingFlags.InvokeMethod, null, shell, new object[] { dirPath }); 2323 2424 //已经压缩进去的文件 2525 int zipFileCount = 0; 2626 2727 // 遍历并压缩源文件夹的文件到Zip中,因为压缩需要消耗时间需要进行等待 2828 foreach (var file in srcFolder.Items()) 2929 { 3030 destFile.CopyHere(file, 4 | 16); 3131 zipFileCount++; 3232 3333 // 判断后进行等待 3434 while (destFile.Items().Count < zipFileCount) 3535 { 3636 // 因为压缩需要消耗时间需要进行等待 3737 System.Threading.Thread.Sleep(10); 3838 } 3939 } 4040 }
需要引用的DLL
C:\Windows\System32\Shell32.dll 嵌入互操作类型为False
注意:CopyHere中的那个枚举参数建议使用代码中的值不需要做其它处理,其它参数值可参见 http://blog.csdn.net/wzhiu/article/details/18224725