Using Image.FromFile does not release handle on a

2019-03-25 13:15发布

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?

3条回答
闹够了就滚
2楼-- · 2019-03-25 13:31

You can try:

resultTiff = null;
查看更多
爷的心禁止访问
3楼-- · 2019-03-25 13:43

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.

查看更多
Animai°情兽
4楼-- · 2019-03-25 13:49

Or try:

Using(Bitmap resultTiff = (Bitmap) Image.FromFile(strImageFile))
{
   ep.Param[0] = new EncoderParameter(enc, (long) EncoderValue.Flush);
   resultTiff.SaveAdd(ep);
}
查看更多
登录 后发表回答