C#中用SharpZipLib.dll實現壓縮解壓2

來源:互聯網
上載者:User
/*******************************************************
著作權:
用    途:檔案壓縮類

結構組成:

說    明:靠調用CSharpCode.SharpZipLib.dll類庫來實現對檔案的壓縮和解壓。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;
using System.Threading;

namespace Framework.Utility.FileHelper
{
    class SharpZipHelper
    {
        #region 壓縮指定檔案產生ZIP檔案
        /// <summary>
        /// 壓縮指定檔案產生ZIP檔案
        /// </summary>
        /// <param name="fileNamesToZip">待壓縮檔列表(絕對路徑)</param>
        /// <param name="ZipedFileName">ZIP檔案(絕對路徑)</param>
        /// <param name="CompressionLevel">壓縮比</param>
        /// <param name="password">密碼</param>
        /// <param name="comment">壓縮檔注釋文字</param>
        /// <returns>返回錯誤資訊</returns>
        public static string ZipFile(string[] fileNamesToZip, string ZipedFileName, int CompressionLevel, string password, string comment)
        {
            try
            {
                System.Text.RegularExpressions.Regex regPath = new System.Text.RegularExpressions.Regex(@"^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w   ]*.*))");
                if (!regPath.Match(ZipedFileName).Success)
                {
                    File.Delete(ZipedFileName);
                    return "壓縮檔的路徑不正確!";
                }
                ZipOutputStream s = new ZipOutputStream(File.Open(ZipedFileName, FileMode.OpenOrCreate));
                if (password != null && password.Length > 0)
                    s.Password = password;
                if (comment != null && comment.Length > 0)
                    s.SetComment(comment);
                s.SetLevel(CompressionLevel); // 0 - means store only to 9 - means best compression   

                foreach (string file in fileNamesToZip)
                {
                    FileStream fs = File.OpenRead(file);    //開啟待壓縮檔   
                    if (!regPath.Match(ZipedFileName).Success)
                    {
                        File.Delete(ZipedFileName);
                        return "待壓縮的檔案路徑不正確!";
                    }
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);      //讀取檔案流   
                    ZipEntry entry = new ZipEntry(Path.GetFileName(file));    //建立執行個體   

                    entry.DateTime = DateTime.Now;

                    entry.Size = fs.Length;
                    fs.Close();

                    s.PutNextEntry(entry);
                    s.Write(buffer, 0, buffer.Length);
                }
                s.Finish();
                s.Close();
            }
            catch(Exception err)
            {
                File.Delete(ZipedFileName);
                return err.Message;
            }
            return "";
        }
        public static void ZipFile(string[] fileNamesToZip, string ZipedFileName, int CompressionLevel, string password)
        {
            ZipFile(fileNamesToZip, ZipedFileName, CompressionLevel, password, null);
        }
        public static void ZipFile(string[] fileNamesToZip, string ZipedFileName, int CompressionLevel)
        {
            ZipFile(fileNamesToZip, ZipedFileName, CompressionLevel, null);
        }
        #endregion

        #region UnZipFile:解壓縮ZIP檔案到指定檔案夾
        /// <summary>   
        /// 解壓縮ZIP檔案到指定檔案夾   
        /// </summary>   
        /// <param name="zipfileName">ZIP檔案(實體路徑)</param>   
        /// <param name="UnZipDir">解壓檔案夾(實體路徑)</param>   
        /// <param name="password">壓縮檔密碼</param> 
        /// <returns>返回錯誤資訊</returns>
        public static string UnZipFile(string zipfileName, string UnZipDir, string password)
        {
            if (!File.Exists(zipfileName))
                return "待解壓的檔案路徑不存在!";
            ZipInputStream s = new ZipInputStream(File.OpenRead(zipfileName));
            if (password != null && password.Length > 0)
                s.Password = password;
            try
            {
                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    if (Directory.Exists(UnZipDir))
                    {
                        Directory.CreateDirectory(UnZipDir);
                    }
                    string directoryName = Path.GetDirectoryName(UnZipDir);
                    string pathname = Path.GetDirectoryName(theEntry.Name);
                    string fileName = Path.GetFileName(theEntry.Name);

                    //產生解壓目錄    
                    pathname = pathname.Replace(":", "$");//處理壓縮時帶有盤符的問題   
                    directoryName = directoryName + "\\" + pathname;
                    Directory.CreateDirectory(directoryName);

                    if (fileName != String.Empty)
                    {
                        //解壓檔案到指定的目錄   
                        FileStream streamWriter = File.Create(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();
            }
            catch (Exception eu)
            {
                return eu.Message;
            }
            finally
            {
                s.Close();
            }
            return "";
        }

        public static void UnZipFile(string zipfileName, string UnZipDir)
        {
            UnZipFile(zipfileName, UnZipDir, null);
        }
        #endregion
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.