Using Image.FromFile does not release handle on a

2019-03-25 12:43发布

问题:

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?

回答1:

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.



回答2:

Or try:

Using(Bitmap resultTiff = (Bitmap) Image.FromFile(strImageFile))
{
   ep.Param[0] = new EncoderParameter(enc, (long) EncoderValue.Flush);
   resultTiff.SaveAdd(ep);
}


回答3:

You can try:

resultTiff = null;