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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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.
Method 2
Or try:
Using(Bitmap resultTiff = (Bitmap) Image.FromFile(strImageFile))
{
ep.Param[0] = new EncoderParameter(enc, (long) EncoderValue.Flush);
resultTiff.SaveAdd(ep);
}
Method 3
You can try:
resultTiff = null;
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0