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?
You can try:
The best way to solve the issue with
Image.FromFile
wherein it leaves file handles open is to useImage.FromStream
instead.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.
Or try: