LoginSignup
12
9

More than 5 years have passed since last update.

SharpZipLibを使ってパスワード付きでZip/Unzipする

Last updated at Posted at 2014-05-30
  byte[] _zip;

    // ZIPデータをメモリ上に作成
    public void DoZip() {
       // zip圧縮済みデータをメモリに書き込むストリーム
        System.IO.MemoryStream zipped = new System.IO.MemoryStream();
        ZipOutputStream zos = new ZipOutputStream(zipped);
       // パスワード
        zos.Password = "hogehoge";

       // 圧縮するデータ
        var inBuffer = new MemoryStream(Encoding.UTF8.GetBytes("てすとですよ"));

        // Zipエントリを作成
        var entry = new ZipEntry("zipEntry");
        zos.PutNextEntry(entry);
        ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(inBuffer, zos, new byte[2048]);
        zos.CloseEntry();

       // "the most important of which is setting IsStreamOwner = false 
       // so that the Close (which is needed to finish up the output) 
       // does not close the underlying memorystream. "
       // https://github.com/icsharpcode/SharpZipLib/wiki/Zip-Samples#-create-a-zip-fromto-a-memory-stream-or-byte-array)

        zos.IsStreamOwner = false;
        zos.Close ();

       // Zip圧縮した結果を16進数表現の文字列として表示
        Debug.Log (BitConverter.ToString(zipped.ToArray()));

        _zip = zipped.ToArray();
    }


    // メモリ上のZIPデータを展開
    public void DoUnzip() {
       // Zip展開した結果を取り出すストリーム
        System.IO.MemoryStream zipped = new System.IO.MemoryStream(_zip);
        ZipInputStream zis = new ZipInputStream(zipped);
       // パスワード(Zip圧縮時のパスワードと同じもの)
        zis.Password = "hogehoge";

        ZipEntry ze;
        while((ze = zis.GetNextEntry()) != null) {
           // Zip展開した結果をメモリに書き出すストリーム
            var outBuffer = new MemoryStream();

           // Zip展開した結果のストリームからメモリに書き出す
            ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(zis, outBuffer, new byte[1024]);
            outBuffer.Close ();

           // 展開した結果を文字列として表示
            Debug.Log ("unzipped: " + Encoding.UTF8.GetString(outBuffer.ToArray()));
        }
        zis.Close ();
        zipped.Close ();
    }

参考

12
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
9