Ronald Ronald -4 years ago 274
C# Question

Image delete c# winfrom

I have an image on my computer that my program uses (loads it to a pictureBox).

at run time !'m trying to delete the picture from my computer,

but there is an error that says the image is open hens why it can not be


I tried this code but it did not work

PICbefore.Image = new Bitmap(Image.FromFile(ofd.FileName));
ProfilePic.Image = null;

Answer Source

I've encountered this before. From memory, the solution is to open a stream to read the file (using a using statement) and then load the bitmap via the stream and assign it. That way you are in complete control of the life cycle of the file/stream and the ProfilePic.Image property never touches the file.

    var filename = @"c:\image.png";
    Image img;
    using (var stream = File.OpenRead(filename))
        img = new Bitmap(stream);
    PICbefore.Image = img;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download