c#壓縮解壓協助類

來源:互聯網
上載者:User

標籤:

using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Web;using ICSharpCode.SharpZipLib.Zip;namespace GzRMIS.Main.Business{    public class ZipHelper    {        /// <summary>        /// 存放待壓縮的檔案的絕對路徑        /// </summary>        private List<string> AbsolutePaths { set; get; }        public string errorMsg { set; get; }        public ZipHelper()        {            errorMsg = "";            AbsolutePaths = new List<string>();        }        /// <summary>        /// 添加壓縮檔或檔案夾        /// </summary>        /// <param name="_fileAbsolutePath">檔案或檔案夾的絕對路徑</param>        public void AddFile(string _fileAbsolutePath)        {            AbsolutePaths.Add(_fileAbsolutePath);        }        /// <summary>        /// 壓縮檔或者檔案夾        /// </summary>        /// <param name="_depositPath">壓縮後檔案的存放路徑   如C:\\windows\abc.zip</param>        ///  <param name="_Level">壓縮層級0~9,數字越大壓縮率越高,預設為5</param>        /// <returns></returns>        public bool CompressionZip(string _depositPath,int _Level=5)        {            bool result = true;            FileStream fs = null;            try            {                ZipOutputStream ComStream = new ZipOutputStream(File.Create(_depositPath));                ComStream.SetLevel(_Level);      //壓縮等級                foreach (string path in AbsolutePaths)                {                    //如果是目錄                    if (Directory.Exists(path))                    {                        ZipFloder(path, ComStream, path);                    }                    else if (File.Exists(path))//如果是檔案                    {                        fs = File.OpenRead(path);                        byte[] bts = new byte[fs.Length];                        fs.Read(bts, 0, bts.Length);                        ZipEntry ze = new ZipEntry(new FileInfo(path).Name);                        ComStream.PutNextEntry(ze);             //為壓縮檔流提供一個容器                        ComStream.Write(bts, 0, bts.Length);  //寫入位元組                    }                }                ComStream.Finish(); // 結束壓縮                ComStream.Close();            }            catch (Exception ex)            {                if (fs != null)                {                    fs.Close();                }                errorMsg = ex.Message;                result = false;            }            return result;        }        //壓縮檔夾        private void ZipFloder(string _OfloderPath, ZipOutputStream zos, string _floderPath)        {            foreach (FileSystemInfo item in new DirectoryInfo(_floderPath).GetFileSystemInfos())            {                if (Directory.Exists(item.FullName))                {                    ZipFloder(_OfloderPath, zos, item.FullName);                }                else if (File.Exists(item.FullName))//如果是檔案                {                    DirectoryInfo ODir = new DirectoryInfo(_OfloderPath);                    string fullName2 = new FileInfo(item.FullName).FullName;                    string path = ODir.Name + fullName2.Substring(ODir.FullName.Length, fullName2.Length - ODir.FullName.Length);//擷取相對目錄                    FileStream fs = File.OpenRead(fullName2);                    byte[] bts = new byte[fs.Length];                    fs.Read(bts, 0, bts.Length);                    ZipEntry ze = new ZipEntry(path);                    zos.PutNextEntry(ze);             //為壓縮檔流提供一個容器                    zos.Write(bts, 0, bts.Length);  //寫入位元組                }            }        }        /// <summary>        /// 解壓        /// </summary>        /// <param name="_depositPath">壓縮檔路徑</param>        /// <param name="_floderPath">解壓的路徑</param>        /// <returns></returns>        public bool DeCompressionZip(string _depositPath, string _floderPath)        {            bool result = true;            FileStream fs = null;            try            {                ZipInputStream InpStream = new ZipInputStream(File.OpenRead(_depositPath));                ZipEntry ze = InpStream.GetNextEntry();//擷取壓縮檔中的每一個檔案                Directory.CreateDirectory(_floderPath);//建立解壓檔案夾                while (ze != null)//如果解壓完ze則是null                {                    if (ze.IsFile)//壓縮zipINputStream裡面存的都是檔案。帶檔案夾的檔案名稱字是檔案夾\\檔案名稱                    {                        string[] strs = ze.Name.Split('\\');//如果檔案名稱中包含’\\‘則表明有檔案夾                        if (strs.Length > 1)                        {                            //兩層迴圈用於一層一層建立檔案夾                            for (int i = 0; i < strs.Length - 1; i++)                            {                                string floderPath = _floderPath;                                for (int j = 0; j < i; j++)                                {                                    floderPath = floderPath + "\\" + strs[j];                                }                                floderPath = floderPath + "\\" + strs[i];                                Directory.CreateDirectory(floderPath);                            }                        }                        fs = new FileStream(_floderPath + "\\" + ze.Name, FileMode.OpenOrCreate, FileAccess.Write);//建立檔案                        //迴圈讀取檔案到檔案流中                        while (true)                        {                            byte[] bts = new byte[1024];                            int i = InpStream.Read(bts, 0, bts.Length);                            if (i > 0)                            {                                fs.Write(bts, 0, i);                            }                            else                            {                                fs.Flush();                                fs.Close();                                break;                            }                        }                    }                    ze = InpStream.GetNextEntry();                }            }            catch (Exception ex)            {                if (fs != null)                {                    fs.Close();                }                errorMsg = ex.Message;                result = false;            }            return result;        }    }}<a target=_blank href="http://icsharpcode.github.io/SharpZipLib/" target="_blank">ICSharpCode.SharpZipLib.Zip下載</a>

c#壓縮解壓協助類

聯繫我們

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