2

That's all there is to this simple program. There's a button, you open an image file, the program puts a watersign on it and overwrites it:

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);
            }
        }
    }

Right now I'm just trying to delete the damned file which for some reason doesn't work. I tried using as you can see, as well as Dispose(), as well as creating another BMP which gets its data from the first one.

Any ideas? Thanks in advance!

momo
  • 119
  • 3
  • 10

1 Answers1

1

The line

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

Loads a bitmap from the file, then creates an independent copy of it using the Bitmap(Image) constructor. Upon exiting the using statement the copy will get disposed -- but not inner bitmap loaded from the file. Until that inner bitmap is eventually finalized by the GC it will maintain a lock on the file as is stated in the docs:

The file remains locked until the Image is disposed.

This prevents you from deleting the file right away.

Assuming you are actually trying to modify the image in the file and save it back to the original location, you could do something like:

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) { }
}

Alternatively, load the file into an intermediate MemoryStream then create the bitmap from the memory stream as suggested here.

dbc
  • 104,963
  • 20
  • 228
  • 340