2019-08-06に投稿

【C#】7zipを使ってファイル・フォルダの圧縮をしてみる

今回は画面で選択したファイルやフォルダをまとめて圧縮してみようと思います。
圧縮するためのライブラリで、圧縮率の高さなどが人気の「7zip」というツールを使用します。

プログラムは前回のものを流用します。

【C#】ListViewの項目を別のListViewへ追加する

7zipのdllを入手、配置

下記サイトより入手。
http://www.vector.co.jp/soft/win95/util/se252429.html

作者:秋田 稔 様
http://www.vector.co.jp/vpack/browse/person/an018964.html

パッケージエクスプローラー

ダウンロードした「7-zip32.dll」をプロジェクトの直下にコピーします。

プロパティ画面

プロパティから「出力ディレクトリにコピー」オプションを「常にコピーする」に変更します。

画面の修正

ボタンの追加

画面に圧縮ボタン、展開ボタン(今回は未使用)を追加

プログラムの修正

ライブラリ使用宣言の追加

実行ディレクトリのパスを取得するために利用

using System.Reflection;

新規メソッドの追加

圧縮対象のフォルダを一時ディレクトリにコピーするために再帰処理をするメソッドを追加

            /// <summary>
            /// ディレクトリをコピーする
            /// </summary>
            /// <param name="from">コピー元</param>
            /// <param name="to">コピー先</param>
            public static void CopyDirectory(string from, string to)
            {
                // ディレクトリが存在しない場合は作成
                if (!Directory.Exists(to))
                {
                    Directory.CreateDirectory(to);
                    File.SetAttributes(to,File.GetAttributes(from));
                }

                // コピー先のディレクトリ名の末尾に"\"をつける
                if (!to.EndsWith(Path.DirectorySeparatorChar.ToString()))
                {
                    to += Path.DirectorySeparatorChar;
                }

                // コピー元のディレクトリにあるファイルをコピー
                string[] files = Directory.GetFiles(from);
                foreach (string file in files)
                {
                    File.Copy(file, to + Path.GetFileName(file), true);
                }

                // サブディレクトリを再帰処理する
                string[] dirs = Directory.GetDirectories(from);
                foreach (string dir in dirs)
                {
                    CopyDirectory(dir, to + Path.GetFileName(dir));
                }
            }

圧縮ボタンクリックイベントの追加

            /// <summary>
            /// 圧縮ボタンクリックイベント.
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void btnCompless_Click(object sender, EventArgs e)
            {

                // 実行ディレクトリパスの取得
                Assembly mainAssembly = Assembly.GetExecutingAssembly();
                // 実行フォルダ取得
                string appDir = Path.GetDirectoryName(mainAssembly.Location);
                // 一時フォルダパス
                string copyTo = appDir + "\\Compress";

                try
                {
                    // なければ作成
                    if (!Directory.Exists(copyTo))
                    {
                        Directory.CreateDirectory(copyTo);
                    }

                    // 選択されたファイルを一時ディレクトリにコピー
                    var selectedItems = listView1.SelectedItems;
                    foreach (ListViewItem item in selectedItems)
                    {
                        // ファイル・ディレクトリを判定
                        if (File.Exists(item.Name))
                        {
                            // 存在する場合は上書きする
                            File.Copy(item.Name, copyTo + "\\" + item.Text, true);
                        }
                        else if (Directory.Exists(item.Name))
                        {
                            // サブディレクトリも再帰処理でコピーする
                            CopyDirectory(item.Name, copyTo);
                        }

                    }

                    // 圧縮処理
                    IntPtr hWnd = this.Handle;
                    StringBuilder strShortPath = new StringBuilder(1024);
                    GetShortPathName(copyTo, strShortPath, 1024);

                    // zip圧縮
                    string strCommandLine = "a -tzip archive.zip " + strShortPath.ToString() + "\\*";

                    // 7z圧縮
                    // string strCommandLine = "a -t7z archive.7z " + strShortPath.ToString() + "\\*";

                    // zip超圧縮
                    //string strCommandLine = "a -tzip archive.zip " + strShortPath.ToString() + "\\* -mx9";

                    // zip無圧縮
                    //string strCommandLine = "a -tzip archive.zip " + strShortPath.ToString() + "\\* -mx0";

                    // zipパスワード("password")付圧縮(処理状況ダイアログ非表示)
                    //string strCommandLine = "a -tzip -hide archive.zip " + strShortPath.ToString() + "\\* -ppassword";

                    // 7zパスワード("password")付圧縮(書庫のヘッダも暗号化)
                    //string strCommandLine = "a -t7z archive.7z " + strShortPath.ToString() + "\\* -ppassword -mhe";

                    StringBuilder strOutPut = new StringBuilder(1024);
                    int ret = SevenZip(hWnd, strCommandLine, strOutPut, 1024);
                    if (ret == 0)
                    {
                        MessageBox.Show(appDir + "に archive.zip を作成しました。", "圧縮処理");
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "圧縮エラー");
                }
                finally
                {
                    //Directory.Delete(copyTo, true);
                }

            }

起動してみる

対象のファイルを選択

対象のファイル(今回はフォルダ)を選択して「追加」ボタンをクリック、下のリストに追加されたら「圧縮」ボタンをクリックします。

圧縮中

ちゃんと圧縮中のプログレスダイアログも表示できます。

完了メッセージ

無事に圧縮ファイルを作成できました。

まとめ

ちょっと長くなったので、展開(解凍)はまた次回。

ではでは。

 

Originally published at www.doraxdora.com
ツイッターでシェア
みんなに共有、忘れないようにメモ

doraxdora

IT関係の仕事をしています/1985年生まれの東京在住/便利なサービスやツール漁りや料理などが好き/2017年~ブログやってます/自分でサービスとか作ってリリースしたい/何かありましたらお気軽にDMどうぞ

Crieitは誰でも投稿できるサービスです。 是非記事の投稿をお願いします。どんな軽い内容でも投稿できます。

また、「こんな記事が読みたいけど見つからない!」という方は是非記事投稿リクエストボードへ!

有料記事を販売できるようになりました!

こじんまりと作業ログやメモ、進捗を書き残しておきたい方はボード機能をご利用ください。
ボードとは?

コメント