pandazx's blog

データ分析など雑多な技術ブログ

C#でzipファイルの16進数文字列をバイナリにして出力

zipファイルのバイナリをテキストダンプした後で
解凍して中身を取り出したい場合のサンプルコード。
以下の例では結果をD:\test.zip として出力する。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace unzipTextBinary
{
  class Program
  {
    static void Main(string[] args)
    {
      // zipファイルの先頭の0xを除外した16進数文字列(半角スペース区切りと仮定)
      string s = "50 4B 03 04 0A 00 00 00 00 00 0A 97 82 45 AA E2 67 8C 1C 00 00 00 1C 00 00 00 08 00 00 00 74 65 73 74 2E 74 78 74 82 B1 82 EA 82 CD 0D 0A 83 65 83 58 83 67 0D 0A 83 74 83 40 83 43 83 8B 82 C5 82 B7 50 4B 01 02 14 00 0A 00 00 00 00 00 0A 97 82 45 AA E2 67 8C 1C 00 00 00 1C 00 00 00 08 00 00 00 00 00 00 00 00 00 20 00 00 00 00 00 00 00 74 65 73 74 2E 74 78 74 50 4B 05 06 00 00 00 00 01 00 01 00 36 00 00 00 42 00 00 00 00 00";

      // 文字列をバイナリに変換
      int i, j;
      int len = s.Length / 3;
      byte[] bs = new byte[len+10];
      j = 0;
      for (i = 0; i < len; i++)
      {
        bs[i] = Convert.ToByte("0x" + s.Substring(j, 2), 16);
        j += 3;
      }

      // 出力
      System.IO.FileStream fs = new System.IO.FileStream(
        @"D:\test.zip",
        System.IO.FileMode.Create,
        System.IO.FileAccess.Write);
        fs.Write(bs, 0, bs.Length);
        fs.Close();
    }
  }
}

test.zip を解凍すると、test.txt が出てきて、中身は以下の通り。

これは
テスト
ファイルです