たるきちのあれこれ









  Topプログラミングサンプル ▶ 圧縮ファイルの作成、展開

秋田 稔様作の「7-zip32.dll」を使用させていただきます。
「7-zip32.dll」を実行ファイルと同じフォルダに置いて作成します。


圧縮ファイル作成のサンプルです。

C#  圧縮ファイル作成

// using System.Runtime.InteropServices;

[DllImport("7-zip32.dll", CharSet = CharSet.Ansi)]
private static extern int SevenZip(IntPtr hWnd, string strCommandLine, StringBuilder strOutPut, uint outputSize);
[DllImport("kernel32.dll")]
private static extern uint GetShortPathName(string strLongPath, StringBuilder strShortPath, uint buf);

private void DirToZip(string strDirPath)
{
    IntPtr hWnd = this.Handle;
    StringBuilder strShortPath = new StringBuilder(1024);
    GetShortPathName(strDirPath, strShortPath, 1024);
    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);
}

DirToZip(@"C:\sample");



圧縮ファイル展開のサンプルです。

C#  圧縮ファイル展開

// using System.Runtime.InteropServices;

[DllImport("7-zip32.dll", CharSet = CharSet.Ansi)]
private static extern int SevenZip(IntPtr hWnd, string strCommandLine, StringBuilder strOutPut, uint outputSize);
[DllImport("kernel32.dll")]
private static extern uint GetShortPathName(string strLongPath, StringBuilder strShortPath, uint buf);

private void ZipToDir(string strArchive)
{
    IntPtr hWnd = this.Handle;
    StringBuilder strShortPath = new StringBuilder(1024);
    GetShortPathName(strArchive, strShortPath, 1024);
    string strCommandLine = "e " + strShortPath.ToString() + " -o*";
    StringBuilder strOutPut = new StringBuilder(1024);
    int ret = SevenZip(hWnd, strCommandLine, strOutPut, 1024);
}

ZipToDir(@"C:\archive.zip");