69

一連のバイト配列から .NET 4.5 (System.IO.Compression) で Zip ファイルを作成しようとしています。例として、私が使用している API から、最終的に が得られ、List<Attachment>それぞれAttachmentに と呼ばれるプロパティBodyがありbyte[]ます。そのリストを反復処理して、各添付ファイルを含む zip ファイルを作成するにはどうすればよいですか?

現在、各添付ファイルをディスクに書き込み、そこから zip ファイルを作成する必要があるという印象を受けています。

//This is great if I had the files on disk
ZipFile.CreateFromDirectory(startPath, zipPath);
//How can I create it from a series of byte arrays?
4

3 に答える 3

127

もう少し遊んで読んだ後、私はこれを理解することができました。一時データをディスクに書き込むことなく、複数のファイルを含む zip ファイル (アーカイブ) を作成する方法を次に示します。

using (var compressedFileStream = new MemoryStream())
{
    //Create an archive and store the stream in memory.
    using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Create, false)) {
        foreach (var caseAttachmentModel in caseAttachmentModels) {
            //Create a zip entry for each attachment
            var zipEntry = zipArchive.CreateEntry(caseAttachmentModel.Name);

            //Get the stream of the attachment
            using (var originalFileStream = new MemoryStream(caseAttachmentModel.Body))
            using (var zipEntryStream = zipEntry.Open()) {
                //Copy the attachment stream to the zip entry stream
                originalFileStream.CopyTo(zipEntryStream);
            }
        }
    }

    return new FileContentResult(compressedFileStream.ToArray(), "application/zip") { FileDownloadName = "Filename.zip" };
}
于 2013-06-20T18:14:04.660 に答える