C#文件或文件夾壓縮和解壓


C#文件或文件夾壓縮和解壓方法有很多,本文通過使用ICSharpCode.SharpZipLib.dll來進行壓縮解壓

1、新建一個winform項目,選擇項目右鍵 管理NuGet程序包,搜索ICSharpCode.SharpZipLib,進行安裝,

如下所示

 

 

2、項目winform窗體添加測試按鈕 壓縮和解壓

 

 

 3、具體代碼如下

using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApp2._0
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Button12_Click(object sender, EventArgs e)
        {
            ZipFile(@"F:\Person\Longteng\LongtengSln\WindowsFormsApp2.0\bin\Debug\devicelog", @"F:\Person\Longteng\LongtengSln\WindowsFormsApp2.0\bin\Debug\devicelog.zip");
            MessageBox.Show("壓縮  成功");
        }

        private void Button13_Click(object sender, EventArgs e)
        {
            UnZipFile(@"F:\Person\Longteng\LongtengSln\WindowsFormsApp2.0\bin\Debug\devicelog.zip", @"F:\Person\Longteng\LongtengSln\WindowsFormsApp2.0\bin\Debug\devicelog11");
            MessageBox.Show("解壓   成功");
        }

        public void ZipFile(string strFile, string strZip)
        {
            if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar)
            {
                strFile += Path.DirectorySeparatorChar;
            }
            ZipOutputStream outstream = new ZipOutputStream(File.Create(strZip));
            outstream.SetLevel(6);
            ZipCompress(strFile, outstream, strFile);
            outstream.Finish();
            outstream.Close();
        }

        public void ZipCompress(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))
                {
                    ZipCompress(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);
                }
            }
        }

        public string UnZipFile(string TargetFile, string fileDir)
        {
            string rootFile = "";
            try
            {
                if (!Directory.Exists(fileDir))
                {
                    Directory.CreateDirectory(fileDir);
                }
                //讀取壓縮文件(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();
                return rootFile;
            }
            catch (Exception ex)
            {
               return ex.Message;
            }
        }

        /// <summary>
        /// 批量壓縮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBatchZipFlo_Click(object sender, EventArgs e)
        {
            string path1 = "D:\\123\\";   //待壓縮的目錄文件
            string path2 = "D:\\456\\";   //壓縮后存放目錄文件
            //獲取指定目錄下所有文件和子文件名稱(所有待壓縮的文件)
            string[] files = Directory.GetFileSystemEntries(path1);
            //ZipFloClass zc = new ZipFloClass();
            //遍歷指定目錄下文件路徑
            foreach (string file in files)
            {
                //截取文件路徑的文件名
                var filename = file.Substring(file.LastIndexOf("\\") + 1);
                //調用壓縮方法(參數1:待壓縮的文件目錄,參數2:壓縮后的文件目錄(包含后綴))
                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:\\123\\";
            string path3 = "D:\\456\\";
            //獲取指定目錄下所有文件和子文件名稱(所有待解壓的壓縮文件)
            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:返工是否解壓成功)
                UnZipFile(file, path3 + filename);
            }
            MessageBox.Show("批量解壓成功");
        }
    }
}

 

原文鏈接:https://www.cnblogs.com/xielong/p/6165550.html


免責聲明!

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



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