Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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
like image 510
Simon_Weaver Avatar asked Apr 25 '09 06:04

Simon_Weaver


2 Answers

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.

like image 142
jamiecon Avatar answered Nov 06 '22 01:11

jamiecon


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

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

like image 23
Steven Avatar answered Nov 06 '22 01:11

Steven