Why does Image.FromFile keep a file handle open sometimes?

I am doing a lot of image processing in GDI+ in .NET in an ASP.NET application.

I frequently find that Image.FromFile() is keeping a file handle open.

Why is this? What is the best way to open an image without the file handle being retained.

  • NB: I'm not doing anything stupid like keeping the Image object lying around - and even if I was I woudlnt expect the file handle to be kept active

I went through the same journey as a few other posters on this thread. Things I noted:

  1. Using Image.FromFile does seem unpredictable on when it releases the file handle. Calling the Image.Dispose() did not release the file handle in all cases.

  2. Using a FileStream and the Image.FromStream method works, and releases the handle on the file if you call Dispose() on the FileStream or wrap the whole thing in a Using {} statement as recommended by Kris. However if you then attempt to save the Image object to a stream, the Image.Save method throws an exception "A generic error occured in GDI+". Presumably something in the Save method wants to know about the originating file.

  3. Steven's approach worked for me. I was able to delete the originating file with the Image object in memory. I was also able to save the Image to both a stream and a file (I needed to do both of these things). I was also able to save to a file with the same name as the originating file, something that is documented as not possible if you use the Image.FromFile method (I find this weird since surely this is the most likely use case, but hey.)

So to summarise, open your Image like this:

Image img = Image.FromStream(new MemoryStream(File.ReadAllBytes(path)));

You are then free to manipulate it (and the originating file) as you see fit.


I have had the same problem and resorted to reading the file using

return Image.FromStream(new MemoryStream(File.ReadAllBytes(fileName)));


Image.FromFile keeps the file handle open until the image is disposed. From the MSDN:

"The file remains locked until the Image is disposed."

Use Image.FromStream, and you won't have the problem.

using(var fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
    return Image.FromStream(fs);
}

Edit: (a year and a bit later)

The above code is dangerous as it is unpredictable, at some point in time (after closing the filestream) you may get the dreaded "A generic error occurred in GDI+". I would amend it to:

Image tmpImage;
Bitmap returnImage;

using(var fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
    tmpImage = Image.FromStream(fs);
    returnImage = new Bitmap(tmpImage);
    tmpImage.Dispose();
}

return returnImage;