Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Image.FromFile does not release handle on a file

I'm doing a join of multiple multi-image tiff files to a single multi-image tiff file and have a problem with deleting the source tiff files, because the Image class continues to hold the handle on them.

I'm reading a tiff image through Image.FromFile:

Bitmap resultTiff = (Bitmap) Image.FromFile(strImageFile);

After which I read all other tiff images the same way and append them to the resulting tiff image.

When I finish I use this code to release references and to save resulting file:

ep.Param[0] = new EncoderParameter(enc, (long) EncoderValue.Flush);
resultTiff.SaveAdd(ep);
resultTiff.Dispose();

Now the problem is that the handle on the files still exists (and therefore files can't be deleted) unless I call the GC.Collect() after the resultTiff.Dispose() call.

You can imagine that I don't feel very comfortable by calling GC, so is there any other way of achieving this?

like image 421
Goran Avatar asked Oct 30 '09 11:10

Goran


3 Answers

The best way to solve the issue with Image.FromFile wherein it leaves file handles open is to use Image.FromStream instead.

using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
   using (Image original = Image.FromStream(fs))
   {
      ...

Using an explicit Dispose(), a using() statement or setting the value to null doesn't solve the issue until a garbage collection happens. Forcing a garbage collection to happen is generally a bad idea.

like image 113
Ian Mercer Avatar answered Nov 01 '22 02:11

Ian Mercer


Or try:

Using(Bitmap resultTiff = (Bitmap) Image.FromFile(strImageFile))
{
   ep.Param[0] = new EncoderParameter(enc, (long) EncoderValue.Flush);
   resultTiff.SaveAdd(ep);
}
like image 31
Ralf de Kleine Avatar answered Nov 01 '22 03:11

Ralf de Kleine


You can try:

resultTiff = null;
like image 41
fARcRY Avatar answered Nov 01 '22 04:11

fARcRY