using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using ICSharpCode.SharpZipLib; using ICSharpCode.SharpZipLib.Zip; using ICSharpCode.SharpZipLib.Checksums; namespace Unzip { class Unzip { /// <summary> /// 解壓一個文件 /// </summary> /// <param name="zipFilePath">需要解壓文件所在的路徑</param> /// <param name="targetFilePath">將zip解壓到此目錄下</param> /// <returns></returns> public static void UnZipFile(string zipFilePath, string targetFilePath) { ZipInputStream zipInputStream = null; FileStream streamWrite = null; ZipEntry ent = null; string fileName;//解壓文件時讀寫zip文件所用的變量 // 去掉文件夾或文件的只讀屬性 if (true == Directory.Exists(zipFilePath)) { System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(zipFilePath); directoryInfo.Attributes = FileAttributes.Normal; } //創建目錄 if (!Directory.Exists(targetFilePath)) Directory.CreateDirectory(targetFilePath); //遍歷文件夾 DirectoryInfo theFolder = new DirectoryInfo(zipFilePath); DirectoryInfo[] dirInfo = theFolder.GetDirectories(); foreach (DirectoryInfo NextFolder in dirInfo) { //遍歷子文件 FileInfo[] fileInfo = NextFolder.GetFiles("*.zip", SearchOption.AllDirectories); foreach (FileInfo NextFile in fileInfo) { try { //去掉只讀屬性 File.SetAttributes(zipFilePath, FileAttributes.Normal); zipInputStream = new ZipInputStream(File.OpenRead(NextFile.FullName)); while ((ent = zipInputStream.GetNextEntry()) != null) { if (!string.IsNullOrEmpty(ent.Name)) { fileName = Path.Combine(targetFilePath + @"\" + NextFolder.Name, ent.Name); fileName = fileName.Replace('/', '\\'); if (fileName.EndsWith("\\")) { Directory.CreateDirectory(fileName); continue; } streamWrite = File.Create(fileName); int size = 2048; byte[] data = new byte[size]; while (true) { size = zipInputStream.Read(data, 0, data.Length); if (size > 0) streamWrite.Write(data, 0, size); else break; } } } } catch(Exception ex) { throw ex; } finally { if (streamWrite != null) { streamWrite.Close(); streamWrite.Dispose(); } if (zipInputStream != null) { zipInputStream.Close(); zipInputStream.Dispose(); } if (ent != null) { ent = null; } GC.Collect(); GC.Collect(1); } } } }