使用Image.FromFile不会释放文件句柄

时间:2022-07-22 21:23:33

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.

我正在将多个多图像tiff文件连接到单个多图像tiff文件,并且在删除源tiff文件时遇到问题,因为Image类继续保持它们的句柄。

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

我正在通过Image.FromFile读取tiff图像:

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.

之后我以相同的方式读取所有其他tiff图像并将它们附加到生成的tiff图像。

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.

现在的问题是文件句柄仍然存在(因此文件无法删除),除非我在resultTiff.Dispose()调用之后调用GC.Collect()。

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

您可以想象通过调用GC我感觉不舒服,那么还有其他方法可以实现吗?

3 个解决方案

#1


17  

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

使用Image.FromFile解决问题的最佳方法是使用Image.FromStream。

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.

使用显式Dispose(),using()语句或将值设置为null在垃圾收集发生之前不能解决问题。强制垃圾收集发生通常是个坏主意。

#2


5  

Or try:

或尝试:

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

#3


1  

You can try:

你可以试试:

resultTiff = null;

#1


17  

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

使用Image.FromFile解决问题的最佳方法是使用Image.FromStream。

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.

使用显式Dispose(),using()语句或将值设置为null在垃圾收集发生之前不能解决问题。强制垃圾收集发生通常是个坏主意。

#2


5  

Or try:

或尝试:

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

#3


1  

You can try:

你可以试试:

resultTiff = null;