2013年2月28日木曜日

Zip を一括で解凍するプログラム

指定したフォルダ内の Zip ファイルをすべて解凍するプログラムです。
解凍するファイルと同じ名前のフォルダを、ファイルがあるフォルダー内に作成し、
そこへ解凍します。

Zip の解凍には、DotNetZip を使用しました。
MS Visual Studio に Ionic.Zip.dll を 参照の追加 しています。

DotNetZip - Zip and Unzip in C#, VB, any .NET language
http://dotnetzip.codeplex.com/

DotNetZip の Ver.1.9 を利用したのですが、日本語対応の部分で、
Ver.1.8 のサンプルがそのまま使えませんでした。
オプションの指定を、予め ReadOptions 変数(options)に用意しておいてから
指定することでうまくいきました。(プログラムの青字部分)


AllUnZip.exe  C#  WinDesktop
Form1 に button1 button2 と label1 を配置


Form1.cs

=====================================================================

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

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

        private void button1_Click(object sender, EventArgs e)
        {
            string selectPath = null;

            try
            {
                // string selectPath = string.Empty;
                selectPath = string.Empty;
                label1.Text = "フォルダを選択 解凍実行";
                label1.Update();
                // FolderBrowserDialog の新しいインスタンスを生成する (デザイナから追加している場合は必要ない)
                FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();

                // ダイアログの説明を設定する
                folderBrowserDialog1.Description = "フォルダを選択";

                // ルートになる特殊フォルダを設定する (初期値 SpecialFolder.Desktop)
                // folderBrowserDialog1.RootFolder = System.Environment.SpecialFolder.MyDocuments;

                // 初期選択するパスを設定する
                // RootFolder以下にあるフォルダである必要がある
                // folderBrowserDialog1.SelectedPath = @"C:\Program Files\";
                folderBrowserDialog1.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

                // [新しいフォルダ] ボタンを表示する (初期値 true)
                folderBrowserDialog1.ShowNewFolderButton = false;

                // ダイアログを表示し、戻り値が [OK] の場合は、選択したディレクトリをする
                if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                {

                    if (Directory.Exists(folderBrowserDialog1.SelectedPath))
                    {
                        selectPath = folderBrowserDialog1.SelectedPath;
                    }
                    else
                    {
                        label1.Text = "フォルダが実在しません";
                        return;
                    }
                }
                else
                {
                    label1.Text = "解凍中止";
                    return;
                }
               
                if (!string.IsNullOrEmpty(selectPath))
                {
                    // 提出モードの処理を実行する
                    this.UnCompress(selectPath);
                }
                // 不要になった時点で破棄する
                folderBrowserDialog1.Dispose();
               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                label1.Text = "解凍失敗!";
            }


        }

        private void button2_Click(object sender, EventArgs e)
        {
            Environment.Exit(0);

        }

        /// <summary>
        /// 解凍処理を実行する
        /// </summary>
        /// <param name="path">ユーザが選択したフォルダまでのパス</param>
        /// <param name="extention">解凍対象の拡張子(例:"*.gz")。デフォルトは"*.zip"</param>
        ///
        private void UnCompress(string path, string extention = "*.zip")
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(path);
            string savePath = directoryInfo.FullName;

            // ディレクトリ内にある解凍対象を解凍する
            foreach (FileInfo fileInfo in directoryInfo.GetFiles(extention))
            {
                using (FileStream inFile = fileInfo.OpenRead())
                {
                    string currentFile = fileInfo.FullName;
                    string stBaseName = System.IO.Path.GetFileNameWithoutExtension(fileInfo.Name);

                    var options = new ReadOptions
                    {
                        StatusMessageWriter = System.Console.Out,
                        Encoding = System.Text.Encoding.GetEncoding("shift_jis")
                    };

                    using (ZipFile zip = ZipFile.Read(currentFile, options))
                    {
                        if (System.IO.Directory.Exists(savePath + @"\" + stBaseName))
                        {
                            label1.Text = "同名のフォルダが存在する";
                            DialogResult result = MessageBox.Show
                                ("同名のフォルダが存在するためスキップします。
                                   \r\n処理を終了する場合はキャンセル"
                                , "エラー"
                                , MessageBoxButtons.OKCancel
                                , MessageBoxIcon.Hand);
                            if (result == DialogResult.Cancel)
                            {
                                label1.Text = "解凍中断";
                                return;
                            }
                        }
                        else
                        {
                            // 全て解凍する
                            // zip.ExtractAll(savePath + @"\" + stBaseName);

                            // 個別に解凍する
                            foreach (ZipEntry entry in zip)
                            {
                                label1.Text = entry.FileName;
                                label1.Update();
                                // 解凍処理
                                entry.Extract(savePath + @"\" + stBaseName);
                            }
                        }
                    }
                }
            }
            label1.Text = "解凍終了";
        }
    }
}


=====================================================================





0 件のコメント:

コメントを投稿