标签:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.IO; 6 using ICSharpCode.SharpZipLib; 7 using ICSharpCode.SharpZipLib.Zip; 8 using ICSharpCode.SharpZipLib.Checksums; 9 10 namespace Unzip 11 { 12 class Unzip 13 { 14 /// <summary> 15 /// 解压一个文件 16 /// </summary> 17 /// <param name="zipFilePath">需要解压文件所在的路径</param> 18 /// <param name="targetFilePath">将zip解压到此目录下</param> 19 /// <returns></returns> 20 public static void UnZipFile(string zipFilePath, string targetFilePath) 21 { 22 ZipInputStream zipInputStream = null; 23 FileStream streamWrite = null; 24 ZipEntry ent = null; 25 string fileName;//解压文件时读写zip文件所用的变量 26 27 // 去掉文件夹或文件的只读属性 28 if (true == Directory.Exists(zipFilePath)) 29 { 30 System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(zipFilePath); 31 directoryInfo.Attributes = FileAttributes.Normal; 32 } 33 34 //创建目录 35 if (!Directory.Exists(targetFilePath)) 36 Directory.CreateDirectory(targetFilePath); 37 38 //遍历文件夹 39 DirectoryInfo theFolder = new DirectoryInfo(zipFilePath); 40 DirectoryInfo[] dirInfo = theFolder.GetDirectories(); 41 42 foreach (DirectoryInfo NextFolder in dirInfo) 43 { 44 //遍历子文件 45 FileInfo[] fileInfo = NextFolder.GetFiles("*.zip", SearchOption.AllDirectories); 46 47 foreach (FileInfo NextFile in fileInfo) 48 { 49 try 50 { 51 //去掉只读属性 52 File.SetAttributes(zipFilePath, FileAttributes.Normal); 53 54 zipInputStream = new ZipInputStream(File.OpenRead(NextFile.FullName)); 55 56 while ((ent = zipInputStream.GetNextEntry()) != null) 57 { 58 if (!string.IsNullOrEmpty(ent.Name)) 59 { 60 fileName = Path.Combine(targetFilePath + @"\" + NextFolder.Name, ent.Name); 61 fileName = fileName.Replace(‘/‘, ‘\\‘); 62 63 if (fileName.EndsWith("\\")) 64 { 65 Directory.CreateDirectory(fileName); 66 continue; 67 } 68 69 streamWrite = File.Create(fileName); 70 int size = 2048; 71 byte[] data = new byte[size]; 72 73 while (true) 74 { 75 size = zipInputStream.Read(data, 0, data.Length); 76 if (size > 0) 77 streamWrite.Write(data, 0, size); 78 else 79 break; 80 } 81 } 82 } 83 } 84 catch(Exception ex) 85 { 86 throw ex; 87 } 88 finally 89 { 90 if (streamWrite != null) 91 { 92 streamWrite.Close(); 93 streamWrite.Dispose(); 94 } 95 if (zipInputStream != null) 96 { 97 zipInputStream.Close(); 98 zipInputStream.Dispose(); 99 } 100 if (ent != null) 101 { 102 ent = null; 103 } 104 GC.Collect(); 105 GC.Collect(1); 106 } 107 } 108 } 109 } 110 111 112
标签:
原文地址:http://www.cnblogs.com/Revoir/p/5295488.html