文件未被释放,即使使用.Dispose()

时间:2015-06-12 21:51:19

标签: c# .net dispose using

我有一个简单的C#应用​​程序用于重命名和调整图像大小,我有一点问题 - 当它完成所有给定文件的工作时,最后一个总是保留在程序的内存或其他任何内容中,我可以&删除它而不关闭程序。

如何让我的代码在完成后始终释放它所使用的文件?

这就是我所拥有的

     private void processFiles() {
        foreach (string oldFileNamePath in fileEntries) {
            ...
            File.Move(oldFileNamePath, newFileNamePath);
            if (isResizeImage) {
                if (!extension.Equals(".gif")) {
                    Image newImage = Image.FromFile(newFileNamePath);
                    int newWidth = (int) (newImage.Width * (1 + ((double) percentageSize / 100)));
                    int newHeight = (int) (newImage.Height * (1 + ((double) percentageSize / 100)));
                    newImage = ResizeImage(newFileNamePath, newWidth, newHeight);
                    newImage.Save(directory + RESIZED_DIRECTORY + "\\" + newFileName, ImageFormat.Jpeg);
                    newImage.Dispose();
                } else {
                    // only move
                    File.Move(newFileNamePath, directory + RESIZED_DIRECTORY + "\\" + newFileName);
                }
            }
        }
    }

    public static Bitmap ResizeImage(String path, int width, int height) {
        Image image = Image.FromFile(path);
        var destRect = new Rectangle(0, 0, width, height);
        var destImage = new Bitmap(width, height);
        destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
        using (var graphics = Graphics.FromImage(destImage)) {
            // process image
            using (var wrapMode = new ImageAttributes()) {
                wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
            }
        }
        image.Dispose();
        return destImage;
    }
}

1 个答案:

答案 0 :(得分:4)

原始的newImage未被曝光。您正在重新分配它并处理从ResizeImage接收的新图像。

删除以下内容:

Image newImage = Image.FromFile(newFileNamePath);

将您的声明移至下一行。这条线没有做任何事情,因为你在更换之后立即更换它并处理新的替换品,但绝不是原件。

编辑OP后:

你应该这样做:

Image newImage = Image.FromFile(newFileNamePath); 
int newWidth = (int) (newImage.Width * (1 + ((double) percentageSize / 100)));
int newHeight = (int) (newImage.Height * (1 + ((double) percentageSize / 100)));
newImage.Dispose();

Image anotherImage = ResizeImage(newFileNamePath, newWidth, newHeight))
anotherImage.Save(directory + RESIZED_DIRECTORY + "\\" + newFileName, ImageFormat.Jpeg);
anotherImage.Dispose();

出于解释目的,我确实没有使用使用。但通常你应该这样做:

using (Image newImage = Image.FromFile(newFileNamePath))
{
    int newWidth = (int) (newImage.Width * (1 + ((double) percentageSize / 100)));
    int newHeight = (int) (newImage.Height * (1 + ((double) percentageSize / 100)));
    using (Image anotherImage = ResizeImage(newFileNamePath, newWidth, newHeight))
        anotherImage.Save(directory + RESIZED_DIRECTORY + "\\" + newFileName, ImageFormat.Jpeg);
    }
}