C#使用ICSharpCode.SharpZipLib.dll壓縮檔夾和檔案

來源:互聯網
上載者:User

大家可以到http://www.icsharpcode.net/opensource/sharpziplib/ 下載SharpZiplib的最新版本,本文使用的版本為0.86.0.518,支援Zip, GZip, BZip2 和Tar格式,其實沒啥好說的直接上代碼

    /// <summary>    /// Zip壓縮與解壓縮     /// </summary>    public class ZipHelper    {        /// <summary>        /// 壓縮單個檔案        /// </summary>        /// <param name="fileToZip">要壓縮的檔案</param>        /// <param name="zipedFile">壓縮後的檔案</param>        /// <param name="compressionLevel">壓縮等級</param>        /// <param name="blockSize">每次寫入大小</param>        public static void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize)        {            //如果檔案沒有找到,則報錯            if (!System.IO.File.Exists(fileToZip))            {                throw new System.IO.FileNotFoundException("指定要壓縮的檔案: " + fileToZip + " 不存在!");            }             using (System.IO.FileStream ZipFile = System.IO.File.Create(zipedFile))            {                using (ZipOutputStream ZipStream = new ZipOutputStream(ZipFile))                {                    using (System.IO.FileStream StreamToZip = new System.IO.FileStream(fileToZip, System.IO.FileMode.Open, System.IO.FileAccess.Read))                    {                        string fileName = fileToZip.Substring(fileToZip.LastIndexOf("\\") + 1);                         ZipEntry ZipEntry = new ZipEntry(fileName);                         ZipStream.PutNextEntry(ZipEntry);                         ZipStream.SetLevel(compressionLevel);                         byte[] buffer = new byte[blockSize];                         int sizeRead = 0;                         try                        {                            do                            {                                sizeRead = StreamToZip.Read(buffer, 0, buffer.Length);                                ZipStream.Write(buffer, 0, sizeRead);                            }                            while (sizeRead > 0);                        }                        catch (System.Exception ex)                        {                            throw ex;                        }                         StreamToZip.Close();                    }                     ZipStream.Finish();                    ZipStream.Close();                }                 ZipFile.Close();            }        }         /// <summary>        /// 壓縮單個檔案        /// </summary>        /// <param name="fileToZip">要進行壓縮的檔案名稱</param>        /// <param name="zipedFile">壓縮後產生的壓縮檔名</param>        public static void ZipFile(string fileToZip, string zipedFile)        {            //如果檔案沒有找到,則報錯            if (!File.Exists(fileToZip))            {                throw new System.IO.FileNotFoundException("指定要壓縮的檔案: " + fileToZip + " 不存在!");            }             using (FileStream fs = File.OpenRead(fileToZip))            {                byte[] buffer = new byte[fs.Length];                fs.Read(buffer, 0, buffer.Length);                fs.Close();                 using (FileStream ZipFile = File.Create(zipedFile))                {                    using (ZipOutputStream ZipStream = new ZipOutputStream(ZipFile))                    {                        string fileName = fileToZip.Substring(fileToZip.LastIndexOf("\\") + 1);                        ZipEntry ZipEntry = new ZipEntry(fileName);                        ZipStream.PutNextEntry(ZipEntry);                        ZipStream.SetLevel(5);                         ZipStream.Write(buffer, 0, buffer.Length);                        ZipStream.Finish();                        ZipStream.Close();                    }                }            }        }         /// <summary>        /// 壓縮多層目錄        /// </summary>        /// <param name="strDirectory">The directory.</param>        /// <param name="zipedFile">The ziped file.</param>        public static void ZipFileDirectory(string strDirectory, string zipedFile)        {            using (System.IO.FileStream ZipFile = System.IO.File.Create(zipedFile))            {                using (ZipOutputStream s = new ZipOutputStream(ZipFile))                {                    ZipSetp(strDirectory, s, "");                }            }        }         /// <summary>        /// 遞迴遍曆目錄        /// </summary>        /// <param name="strDirectory">The directory.</param>        /// <param name="s">The ZipOutputStream Object.</param>        /// <param name="parentPath">The parent path.</param>        private static void ZipSetp(string strDirectory, ZipOutputStream s, string parentPath)        {            if (strDirectory[strDirectory.Length - 1] != Path.DirectorySeparatorChar)            {                strDirectory += Path.DirectorySeparatorChar;            }                       Crc32 crc = new Crc32();             string[] filenames = Directory.GetFileSystemEntries(strDirectory);             foreach (string file in filenames)// 遍曆所有的檔案和目錄            {                 if (Directory.Exists(file))// 先當作目錄處理如果存在這個目錄就遞迴Copy該目錄下面的檔案                {                    string pPath = parentPath;                    pPath += file.Substring(file.LastIndexOf("\\") + 1);                    pPath += "\\";                    ZipSetp(file, s, pPath);                }                 else // 否則直接壓縮檔                {                    //開啟壓縮檔                    using (FileStream fs = File.OpenRead(file))                    {                         byte[] buffer = new byte[fs.Length];                        fs.Read(buffer, 0, buffer.Length);                         string fileName = parentPath + file.Substring(file.LastIndexOf("\\") + 1);                        ZipEntry entry = new ZipEntry(fileName);                         entry.DateTime = DateTime.Now;                        entry.Size = fs.Length;                         fs.Close();                         crc.Reset();                        crc.Update(buffer);                         entry.Crc = crc.Value;                        s.PutNextEntry(entry);                         s.Write(buffer, 0, buffer.Length);                    }                }            }        }         /// <summary>        /// 解壓縮一個 zip 檔案。        /// </summary>        /// <param name="zipedFile">The ziped file.</param>        /// <param name="strDirectory">The STR directory.</param>        /// <param name="password">zip 檔案的密碼。</param>        /// <param name="overWrite">是否覆蓋已存在的檔案。</param>        public void UnZip(string zipedFile, string strDirectory, string password, bool overWrite)        {             if (strDirectory == "")                strDirectory = Directory.GetCurrentDirectory();            if (!strDirectory.EndsWith("\\"))                strDirectory = strDirectory + "\\";             using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipedFile)))            {                s.Password = password;                ZipEntry theEntry;                 while ((theEntry = s.GetNextEntry()) != null)                {                    string directoryName = "";                    string pathToZip = "";                    pathToZip = theEntry.Name;                     if (pathToZip != "")                        directoryName = Path.GetDirectoryName(pathToZip) + "\\";                     string fileName = Path.GetFileName(pathToZip);                     Directory.CreateDirectory(strDirectory + directoryName);                     if (fileName != "")                    {                        if ((File.Exists(strDirectory + directoryName + fileName) && overWrite) || (!File.Exists(strDirectory + directoryName + fileName)))                        {                            using (FileStream streamWriter = File.Create(strDirectory + directoryName + fileName))                            {                                int size = 2048;                                byte[] data = new byte[2048];                                while (true)                                {                                    size = s.Read(data, 0, data.Length);                                     if (size > 0)                                        streamWriter.Write(data, 0, size);                                    else                                        break;                                }                                streamWriter.Close();                            }                        }                    }                }                 s.Close();            }        }     }

代碼來自網路,略作修改,修改為靜態方法,修改檔案夾遞迴壓縮時的bug..

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.