創作內容

15 GP

C# 壓縮 / 解壓縮 功能實作

作者:貓貓風 ฅ●ω●ฅ│2022-03-21 15:50:55│巴幣:30│人氣:702
.


















C# 壓縮與解壓縮的方式很多,本篇使用最普遍的方式進行實作

只要電腦有安裝 WinRAR 這款軟體就可以正常操作此功能

主要實作幾項功能
(1) 資料夾內所有資料夾壓縮
(2) 單一資料夾壓縮
(3) 單一檔案壓縮  

如果有其他需求可以自行修改此程式

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.Win32;
using System.Diagnostics;
namespace File_Compression
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        string _compress_path = "";
        string _decompress_path = "";
        private void button1_Click(object sender, EventArgs e)
        {
            _sigle_file = false;
            if (_compress_path != "")
            {
                if (ExistsWinRar())
                {
                    DirectoryInfo dir = new DirectoryInfo(_compress_path);
                    foreach (DirectoryInfo dChild in
                    dir.GetDirectories("*"))
                     //找出資料夾內所有資料夾
                    {
                        if (ch_box_compress_day.Checked)
                        {
                            if ((DateTime.Now -dChild.LastWriteTime).Days >
                             Int32.Parse(txt_compress_day.Text))
                            {
                               CompressRar(dChild.FullName, _compress_path +
                               "\\" + dChild);
                            }
                        }
                        else
                        {
                            CompressRar(dChild.FullName,_compress_path +  
                            "\\" + dChild);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("沒有安裝 winrar");
                }
            }
            else
            {
                MessageBox.Show("未選擇要壓縮的資料夾");
            }
        }
        public bool ExistsWinRar()
        {
            string result = string.Empty;
            bool is_exist = false;
            string key =
            @"SOFTWARE\Microsoft\Windows\CurrentVersion\AppPaths\WinRAR.exe";
            RegistryKey registryKey =Registry.LocalMachine.OpenSubKey(key);
            if (registryKey != null)
            {
                result = registryKey.GetValue("").ToString();
                is_exist = true;
            }
            registryKey.Close();
            return is_exist;
        }
        /// <summary>
        /// 將格式為rar的壓縮檔案解壓到指定的目錄
        /// </summary>
        /// <paramname="rarFileName">要解壓rar檔案的路徑</param>
        /// <param name="saveDir">解壓後要儲存到的目錄</param>
        public void DeCompressRar(string rarFileName, string saveDir)
        {
            string regKey =
            @"SOFTWARE\Microsoft\Windows\CurrentVersion\AppPaths\WinRAR.exe";
            RegistryKey registryKey
            =Registry.LocalMachine.OpenSubKey(regKey);
            string winrarPath = registryKey.GetValue("").ToString();
            registryKey.Close();
            string winrarDir =System.IO.Path.GetDirectoryName(winrarPath);
            String commandOptions = string.Format("x{0} {1} -y",  
            rarFileName, saveDir);
            ProcessStartInfo processStartInfo =new ProcessStartInfo();
            processStartInfo.FileName =System.IO.Path.Combine(winrarDir,
            "rar.exe");
            processStartInfo.Arguments =commandOptions;
            processStartInfo.WindowStyle =ProcessWindowStyle.Hidden;
            Process process = new Process();
            process.StartInfo =processStartInfo;
            process.Start();
            process.WaitForExit();
            process.Close();
        }
        /// <summary>
        /// 將目錄和檔案壓縮為rar格式並儲存到指定的目錄
        /// </summary>
        /// <paramname="soruceDir">要壓縮的資料夾目錄</param>
        /// <paramname="rarFileName">壓縮後的rar儲存路徑</param>
        public void CompressRar(string soruceDir, string rarFileName)
        {
            string regKey =
            @"SOFTWARE\Microsoft\Windows\CurrentVersion\AppPaths\WinRAR.exe";
            RegistryKey registryKey
            =Registry.LocalMachine.OpenSubKey(regKey);
            stringwinrarPath = registryKey.GetValue("").ToString();
            registryKey.Close();
            string winrarDir =System.IO.Path.GetDirectoryName(winrarPath);
            String commandOptions = "";
            if (ch_box_compress_complete_delete_file.Checked)//
            {
                if (_sigle_file)
                {
                    String[] Sp_str =soruceDir.Split(new char[] { '.' });
                    String[] Sp_str2 = Sp_str[0].Split(new char[] { '\\'
                    });
                    commandOptions = string.Format("a{0} {1} -ep1 -dw",
                    rarFileName + "\\"+ Sp_str2[Sp_str2.Length - 1],  
                    soruceDir);
                }
                else
                {
                    commandOptions = string.Format("a{0} {1} -ep1 -dw",
                    rarFileName, soruceDir);
                }
               
            }
            else
            {
                if (_sigle_file)
                {
                    String[] Sp_str =soruceDir.Split(new char[] { '.' });
                    String[] Sp_str2 = Sp_str[0].Split(new char[] { '\\'
                    });
                    commandOptions = string.Format("a{0} {1} -ep1",
                    rarFileName + "\\"+ Sp_str2[Sp_str2.Length-1],
                    soruceDir);
                }
                else
                {
                    commandOptions = string.Format("a{0} {1} -ep1",
                    rarFileName, soruceDir);
                }
            }
            ProcessStartInfo processStartInfo =new ProcessStartInfo();
            processStartInfo.FileName =System.IO.Path.Combine(winrarDir,  
            "rar.exe");
            processStartInfo.Arguments =commandOptions;
            processStartInfo.WindowStyle =ProcessWindowStyle.Hidden;
            Process process = new Process();
            process.StartInfo = processStartInfo;
            process.Start();
            process.WaitForExit();
            process.Close();
        }
        private void btn_select_folder_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog path = new FolderBrowserDialog();
            path.ShowDialog();
            _compress_path = path.SelectedPath;
            txt_file_path.Text =_compress_path;
        }
        private void btn_select_compressfile_Click(object       
        sender, EventArgs e)
        {
            OpenFileDialog path = new OpenFileDialog();
            path.Filter = "Text documents (.rar)|*.rar";
            // Filter files by extension
            path.ShowDialog();
            _decompress_path = path.FileName;
            txt_decompress_path.Text =_decompress_path;
        }
        private void btn_decompress_file_Click(object sender, EventArgs
        e)
        {
            String[] sp_str =_decompress_path.Split(new char[]  
            { '\\' });
            //找到檔案跟目錄
            String file_at_menu = "";
            for(int i = 0 ; i < sp_str.Length-1 ; i++)
            {
                if (i == sp_str.Length - 2)
                {
                    file_at_menu += sp_str[i];
                }
                else
                {
                    file_at_menu += sp_str[i] +"\\";
                }
            }
            DeCompressRar(_decompress_path,file_at_menu);
        }
        private void button2_Click(object sender, EventArgs e)
        {
            _sigle_file = false;
            CompressRar(_compress_path,_compress_path);
        }
        bool _sigle_file = false;
        private void button3_Click(object sender, EventArgs e)
        {
            String[] sp_str =_compress_path.Split(new char[] { '\\' });
            _sigle_file = true;
            //找到檔案跟目錄
            String file_at_menu = "";
            for (int i = 0; i < sp_str.Length - 1; i++)
            {
                if (i == sp_str.Length - 2)
                {
                    file_at_menu += sp_str[i];
                }
                else
                {
                    file_at_menu += sp_str[i] +"\\";
                }
            }
            CompressRar(_compress_path,file_at_menu);
        }
        private void button4_Click(object sender, EventArgs e)
        {
            OpenFileDialog path = new OpenFileDialog();
            path.Filter = "Text documents (.*)|*.*";
            // Filter files by extension
            path.ShowDialog();
            _compress_path = path.FileName;
            txt_file_path.Text =_compress_path;
        }
    }
}
 

實際執行畫面

資料夾中含多個資料夾個別單獨壓縮



壓縮完成後如下圖  每個資料夾都被已檔名獨立壓縮成一個檔案


解壓縮

選擇壓縮檔  


執行解壓縮


單一資料夾壓縮


單一檔案壓縮


引用網址:https://home.gamer.com.tw/TrackBack.php?sn=5415166
All rights reserved. 版權所有,保留一切權利

相關創作

同標籤作品搜尋:C#|檔案壓縮|檔案解壓縮|WinRAR|Zip|7Zip|程式設計

留言共 0 篇留言

我要留言提醒:您尚未登入,請先登入再留言

15喜歡★s1234567 可決定是否刪除您的留言,請勿發表違反站規文字。

前一篇:貓咪大戰爭 超級貓咪祭 ... 後一篇:靈魂潮汐 七個願望與神的...

追蹤私訊切換新版閱覽

作品資料夾

JOJO121JOJO喜歡惡靈古堡的你
Hi看更多我要大聲說昨天22:26


face基於日前微軟官方表示 Internet Explorer 不再支援新的網路標準,可能無法使用新的應用程式來呈現網站內容,在瀏覽器支援度及網站安全性的雙重考量下,為了讓巴友們有更好的使用體驗,巴哈姆特即將於 2019年9月2日 停止支援 Internet Explorer 瀏覽器的頁面呈現和功能。
屆時建議您使用下述瀏覽器來瀏覽巴哈姆特:
。Google Chrome(推薦)
。Mozilla Firefox
。Microsoft Edge(Windows10以上的作業系統版本才可使用)

face我們了解您不想看到廣告的心情⋯ 若您願意支持巴哈姆特永續經營,請將 gamer.com.tw 加入廣告阻擋工具的白名單中,謝謝 !【教學】