一括ダウンロードみたいなのをしたくなったので、Webアプリ側でZip圧縮したくなった。割と最近の.Netには標準でCompression名前空間にZipまわりのものがあるので使ってみる。以下ソース。
using System.IO.Compression; using (var z = ZipFile.Open(@"C:\Test\hoge.zip", ZipArchiveMode.Update)) { z.CreateEntryFromFile(@"C:\Source\fuga.txt", @"fuga.txt",CompressionLevel.Optimal); z.CreateEntryFromFile(@"C:\Source\moe.txt", @"moe.txt", CompressionLevel.Optimal); }
解凍後にフォルダ階層もつけておきたい場合は以下の感じ
using System.IO.Compression; using (var z = ZipFile.Open(@"C:\Test\hoge.zip", ZipArchiveMode.Update)) { z.CreateEntryFromFile(@"C:\Source\fuga.txt", @"folder1\fuga.txt",CompressionLevel.Optimal); z.CreateEntryFromFile(@"C:\Source\moe.txt", @"folder2\moe.txt", CompressionLevel.Optimal); }
で、これだと日本語のファイル名が文字化けする。なので文字コード指定する。
using System.IO.Compression; Encoding sjisEnc = Encoding.GetEncoding("Shift_JIS"); using (var z = ZipFile.Open(@"C:\Test\hoge.zip", ZipArchiveMode.Update, sjisEnc)) { z.CreateEntryFromFile(@"C:\Source\fuga.txt", @"folder1\fuga.txt",CompressionLevel.Optimal); z.CreateEntryFromFile(@"C:\Source\moe.txt", @"folder2\moe.txt", CompressionLevel.Optimal); }
あーあと、ZipFileとかのクラスを使う場合は、「System.IO.Compression」と「System.IO.Compression.FileSystem」を参照に追加しておかないとダメみたいよ。