0

次の操作を行っていると、Visual Studio 2005でファイル(noimg100.gif)を更新できません。

これがコードです、

String fileNotFoundPath = context.Server.MapPath("~/common/images/noimg100.gif");
context.Response.ContentType = "image/gif";
Image notFoundImage = Image.FromFile(fileNotFoundPath);
notFoundImage.Save(context.Response.OutputStream, ImageFormat.Gif);

私は何か間違ったことをしていますか、それとも最後に画像を破棄する必要がありますか?

編集:次のリンクを見つけました。ここには、私が使用した方法でImage.FromFileを使用しないように記載されています: http ://support.microsoft.com/kb/309482

4

1 に答える 1

1

ファイルから画像を開くと、画像が存在する限りファイルは開いたままになります。オブジェクトを破棄しないためImage、ガベージ コレクターがオブジェクトをファイナライズして破棄するまで存在し続けます。

コードの最後でオブジェクトを破棄するImageと、ファイルへの書き込みが再び可能になります。

ブロックを使用しusingてオブジェクトを破棄することができます。そうすれば、コードでエラーが発生した場合でも、常に破棄されることが確実になります。

String fileNotFoundPath = context.Server.MapPath("~/common/images/noimg100.gif");
context.Response.ContentType = "image/gif";
using (Image notFoundImage = Image.FromFile(fileNotFoundPath)) {
  notFoundImage.Save(context.Response.OutputStream, ImageFormat.Gif);
}

また、画像を一切変更しないので、解凍してから再圧縮するのはもったいないです。ファイルを開いてストリームに書き込むだけです。

String fileNotFoundPath = context.Server.MapPath("~/common/images/noimg100.gif");
context.Response.ContentType = "image/gif";
using (FileStream notFoundImage = File.OpenRead(fileNotFoundPath)) {
  notFoundImage.CopyTo(context.Response.OutputStream);
}
于 2012-05-22T06:26:05.543 に答える