覆盖BMP文件,不能删除,因为它被另一个进程使用了——Dispose, using不起作用

本文关键字:Dispose 不起作用 using 进程 不能 文件 BMP 删除 因为 覆盖 另一个 | 更新日期: 2023-09-27 18:05:09

这就是这个简单程序的全部内容。有一个按钮,你打开一个图像文件,程序会在上面放一个水符号并覆盖它:

private void button1_Click(object sender, EventArgs e)
    {
        var openDialog = new OpenFileDialog();
        var dialogResult = openDialog.ShowDialog();
        if (dialogResult == DialogResult.OK)
        {
            var file = openDialog.FileName;
            using (var bmp = new Bitmap((Bitmap)Image.FromFile(file)))
            using (var g = Graphics.FromImage(bmp))
            {
                openDialog.Dispose();
                var waterSign = (Bitmap)Properties.Resources.ResourceManager.GetObject("watersign");
                var margin = 15;
                var x = bmp.Width - waterSign.Width - margin;
                var y = bmp.Height - waterSign.Height - margin;
                g.DrawImage(waterSign, new Point(x, y));
                waterSign.Dispose();
            }
            try
            {
                File.Delete(file);
                //bmp2.Save("C:''Temp''huhu.bmp");
                this.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }

现在我正试图删除这个该死的文件,但由于某种原因它不起作用。我尝试使用如您所见,以及Dispose(),以及创建另一个BMP,从第一个获取其数据。

任何想法?提前感谢!

覆盖BMP文件,不能删除,因为它被另一个进程使用了——Dispose, using不起作用

using (var bmp = new Bitmap((Bitmap)Image.FromFile(file)))

从文件中加载位图,然后使用Bitmap(Image)构造函数创建它的独立副本。在退出using语句时,副本将被处理——但不会从文件中加载内部位图。在内部位图最终由GC完成之前,它将保持对文件的锁,如文档中所述:

文件一直处于锁定状态,直到Image被处理。

这可以防止您立即删除文件。

假设您实际上试图修改文件中的图像并将其保存回原始位置,您可以这样做:

Bitmap bmp = null;
try
{
    using (var bmpFromFile = (Bitmap)Image.FromFile(file))
    {
        bmp = new Bitmap(bmpFromFile);
    }
    using (var g = Graphics.FromImage(bmp))
    {
        // Make changes to bmp.
    }
    // Save bmp to a temp file.
    // Delete the original file and move the temp file to that name.
}
finally
{
    // Dispose bmp
    using (bmp) { }
}

或者,将文件加载到中间MemoryStream中,然后按照这里的建议从内存流创建位图。