Free file locked by new Bitmap(filePath)

MrCatacroquer picture MrCatacroquer · Jan 26, 2011 · Viewed 45.2k times · Source

I have the Image of a PictureBox pointing to a certain file "A". At execution time I want to change the Image of the PictureBox to a different one "B" but I get the following error:

"A first chance exception of type 'System.IO.IOException' occurred in mscorlib.dll Additional information: The process cannot access the file "A" because it is being used by another process."

I'm setting the Image as follows:

pbAvatar.Image = new Bitmap(filePath);

How can I unlock the first file?

Answer

Brian picture Brian · Feb 12, 2013

Here is my approach to opening an image without locking the file...

public static Image FromFile(string path)
{
    var bytes = File.ReadAllBytes(path);
    var ms = new MemoryStream(bytes);
    var img = Image.FromStream(ms);
    return img;
}

UPDATE: I did some perf tests to see which method was the fastest. I compared it to @net_progs "copy from bitmap" answer (which seems to be the closest to correct, though does have some issues). I loaded the image 10000 times for each method and calculated the average time per image. Here are the results:

Loading from bytes: ~0.26 ms per image.
Copying from bitmap: ~0.50 ms per image.

The results seem to make sense since you have to create the image twice using the copy from bitmap method.

UPDATE: if you need a BitMap you can do:

return (Bitmap)Image.FromStream(ms);