ユーザーがサイトからすべての画像をダウンロードできるように、簡単なダウンロードサービスを作成しています。これを行うには、すべてを http ストリームに圧縮します。
ただし、すべてがメモリに保存されているようで、zip ファイルが完成して出力が閉じられるまでデータは送信されません。サービスがすぐに送信を開始し、メモリを使いすぎないようにしたい。
public void ProcessRequest(HttpContext context)
{
List<string> fileNames = GetFileNames();
context.Response.ContentType = "application/x-zip-compressed";
context.Response.AppendHeader("content-disposition", "attachment; filename=files.zip");
context.Response.ContentEncoding = Encoding.Default;
context.Response.Charset = "";
byte[] buffer = new byte[1024 * 8];
using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutput = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(context.Response.OutputStream))
{
foreach (string fileName in fileNames)
{
ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName);
zipOutput.PutNextEntry(zipEntry);
using (var fread = System.IO.File.OpenRead(fileName))
{
ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(fread, zipOutput, buffer);
}
}
zipOutput.Finish();
}
context.Response.Flush();
context.Response.End();
}
ファイルの作成中にワーカープロセスのメモリが増加し、送信が完了するとメモリが解放されることがわかります。メモリをあまり使用せずにこれを行うにはどうすればよいですか?