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

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.

Leave a Comment