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

本文关键字:Dispose 释放 文件 | 更新日期: 2023-09-27 17:56:11

>我有一个简单的 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;
    }
}

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

原始新图像未公开。您正在重新分配它并处置新图像新您从 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);
    }
}