C#文件或文件夾壓縮和解壓方法(通過ICSharpCode.SharpZipLib.dll)


我在網上收集一下文件的壓縮和解壓的方法,是通過ICSharpCode.SharpZipLib.dll 來實現的

一、介紹的目錄

第一步:下載壓縮和解壓的 ICSharpCode.SharpZipLib.dll 支持庫

第二步:創建一個壓縮和解壓的demo項目

第三步:查看壓縮和解壓的文件的結果

 

二、demo演示(包括源碼和界面)

1、下載文件壓縮和解壓的支持庫dll ,下載地址:http://pan.baidu.com/s/1pLausnL

2、創建window創建項目

1) 添加引用(文件壓縮和解壓的dll)

2) 編寫文件壓縮和解壓方法

選中項目,創建Model文件夾,添加連個類名,壓縮類(ZipFloClass)和解壓類(UnZipFloClass)

2.1)壓縮類(ZipFloClass)

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

namespace ZipCompressTest.Model
{
    /// <summary>
    /// 壓縮的方法
    /// </summary>
    public  class ZipFloClass
    {
        public void ZipFile(string strFile, string strZip)
        {
            var len = strFile.Length;
            var strlen = strFile[len - 1];
            if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar)
            {
                strFile += Path.DirectorySeparatorChar;
            }
            ZipOutputStream outstream = new ZipOutputStream(File.Create(strZip));
            outstream.SetLevel(6);
            zip(strFile, outstream, strFile);
            outstream.Finish();
            outstream.Close();
        }

        public void zip(string strFile, ZipOutputStream outstream, string staticFile)
        {
            if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar)
            {
                strFile += Path.DirectorySeparatorChar;
            }
            Crc32 crc = new Crc32();
            //獲取指定目錄下所有文件和子目錄文件名稱
            string[] filenames = Directory.GetFileSystemEntries(strFile);
            //遍歷文件
            foreach (string file in filenames)
            {
                if (Directory.Exists(file))
                {
                    zip(file, outstream, staticFile);
                }
                //否則,直接壓縮文件
                else
                {
                    //打開文件
                    FileStream fs = File.OpenRead(file);
                    //定義緩存區對象
                    byte[] buffer = new byte[fs.Length];
                    //通過字符流,讀取文件
                    fs.Read(buffer, 0, buffer.Length);
                    //得到目錄下的文件(比如:D:\Debug1\test),test
                    string tempfile = file.Substring(staticFile.LastIndexOf("\\") + 1);
                    ZipEntry entry = new ZipEntry(tempfile);
                    entry.DateTime = DateTime.Now;
                    entry.Size = fs.Length;
                    fs.Close();
                    crc.Reset();
                    crc.Update(buffer);
                    entry.Crc = crc.Value;
                    outstream.PutNextEntry(entry);
                    //寫文件
                    outstream.Write(buffer, 0, buffer.Length);
                }
            }
        }
    }
}

2.2)解壓類(UnZipFloClass)

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

namespace ZipCompressTest.Model
{
    /// <summary>
    /// 解壓方法
    /// </summary>
    public class UnZipFloClass
    {
        public string unZipFile(string TargetFile, string fileDir, ref string msg)
        {
            string rootFile = "";
            msg = "";
            try
            {
                //讀取壓縮文件(zip文件),准備解壓縮
                ZipInputStream inputstream = new ZipInputStream(File.OpenRead(TargetFile.Trim()));
                ZipEntry entry;
                string path = fileDir;
                //解壓出來的文件保存路徑
                string rootDir = "";
                //根目錄下的第一個子文件夾的名稱
                while ((entry = inputstream.GetNextEntry()) != null)
                {
                    rootDir = Path.GetDirectoryName(entry.Name);
                    //得到根目錄下的第一級子文件夾的名稱
                    if (rootDir.IndexOf("\\") >= 0)
                    {
                        rootDir = rootDir.Substring(0, rootDir.IndexOf("\\") + 1);
                    }
                    string dir = Path.GetDirectoryName(entry.Name);
                    //得到根目錄下的第一級子文件夾下的子文件夾名稱
                    string fileName = Path.GetFileName(entry.Name);
                    //根目錄下的文件名稱
                    if (dir != "")
                    {
                        //創建根目錄下的子文件夾,不限制級別
                        if (!Directory.Exists(fileDir + "\\" + dir))
                        {
                            path = fileDir + "\\" + dir;
                            //在指定的路徑創建文件夾
                            Directory.CreateDirectory(path);
                        }
                    }
                    else if (dir == "" && fileName != "")
                    {
                        //根目錄下的文件
                        path = fileDir;
                        rootFile = fileName;
                    }
                    else if (dir != "" && fileName != "")
                    {
                        //根目錄下的第一級子文件夾下的文件
                        if (dir.IndexOf("\\") > 0)
                        {
                            //指定文件保存路徑
                            path = fileDir + "\\" + dir;
                        }
                    }
                    if (dir == rootDir)
                    {
                        //判斷是不是需要保存在根目錄下的文件
                        path = fileDir + "\\" + rootDir;
                    }

                    //以下為解壓zip文件的基本步驟
                    //基本思路:遍歷壓縮文件里的所有文件,創建一個相同的文件
                    if (fileName != String.Empty)
                    {
                        FileStream fs = File.Create(path + "\\" + fileName);
                        int size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = inputstream.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                fs.Write(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }
                        fs.Close();
                    }
                }
                inputstream.Close();
                msg = "解壓成功!";
                return rootFile;
            }
            catch (Exception ex)
            {
                msg = "解壓失敗,原因:" + ex.Message;
                return "1;" + ex.Message;
            }
        }
    }
}

 3)窗體頁面的調用

3.1)窗體布局

3.2)對應的調用方法

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZipCompressTest.Model;

namespace ZipCompressTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 壓縮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnZipFlo_Click(object sender, EventArgs e)
        {
            string[] strs = new string[2];
            //待壓縮文件目錄
            strs[0] = "D:\\DeBug1\\";
            //壓縮后的目標文件
            strs[1] = "D:\\Debug2\\FrpTest.zip";
            ZipFloClass zc = new ZipFloClass();
            zc.ZipFile(strs[0], strs[1]);
        }

        /// <summary>
        /// 解壓事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUnZipFlo_Click(object sender, EventArgs e)
        {
            string[] strs = new string[2];
            string msg = "";
            //待解壓的文件
            strs[0] = "D:\\Debug2\\FrpTest.zip";
            //解壓后放置的目標文件
            strs[1] = "D:\\Debug3\\";
            UnZipFloClass uzc = new UnZipFloClass();
            uzc.unZipFile(strs[0], strs[1], ref msg);
            MessageBox.Show("信息:" + msg);
        }

        /// <summary>
        /// 批量壓縮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBatchZipFlo_Click(object sender, EventArgs e)
        {
            string path1 = "D:\\DeBug1\\";   //待壓縮的目錄文件
            string path2 = "D:\\Debug2\\";   //壓縮后存放目錄文件
            //獲取指定目錄下所有文件和子文件名稱(所有待壓縮的文件)
            string[] files = Directory.GetFileSystemEntries(path1);
            ZipFloClass zc = new ZipFloClass();
            //遍歷指定目錄下文件路徑
            foreach (string file in files)
            {
                //截取文件路徑的文件名
                var filename = file.Substring(file.LastIndexOf("\\") + 1);
                //調用壓縮方法(參數1:待壓縮的文件目錄,參數2:壓縮后的文件目錄(包含后綴))
                zc.ZipFile(path1 + filename, path2 + filename + ".zip");
            }
        }

        /// <summary>
        /// 批量解壓事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBatchUnZipFlo_Click(object sender, EventArgs e)
        {
            string msg = "";
            string path2 = "D:\\Debug2\\";
            string path3 = "D:\\Debug3\\";
            //獲取指定目錄下所有文件和子文件名稱(所有待解壓的壓縮文件)
            string[] files = Directory.GetFileSystemEntries(path2);
            UnZipFloClass uzc = new UnZipFloClass();
            //遍歷所有壓縮文件路徑
            foreach (string file in files)
            {
                //獲取壓縮包名稱(包括后綴名)
                var filename  = file.Substring(file.LastIndexOf("\\") + 1);
                //得到壓縮包名稱(沒有后綴)
                filename = filename.Substring(0, filename.LastIndexOf("."));
                //判斷解壓的路徑是否存在
                if (!Directory.Exists(path3 + filename))
                {
                    //沒有,則創建這個路徑
                    Directory.CreateDirectory(path3 + filename);
                }
                //調用解壓方法(參數1:待解壓的壓縮文件路徑(帶后綴名),參數2:解壓后存放的文件路徑,參數3:返工是否解壓成功)
                uzc.unZipFile(file, path3 + filename, ref msg);
            }
            MessageBox.Show("批量解壓成功");
        }
    }
}

 3.3) 物理路徑創建3個文件,Dubug1,Dubug2,Dubug3

 3、測試結果界面

3.1)demo 程序的界面

3.2)批量壓縮/解壓文件視圖

3.3)批量壓縮的結果視圖

3.4) 批量解壓的結果視圖

三、demo源碼下載

下載demo的路徑: http://pan.baidu.com/s/1o7WsDCm

 

參考資料來源:http://www.cnblogs.com/zfanlong1314/p/4202695.html#commentform

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM