Search code examples
c#imagefilepicturebox

Free file locked by new Bitmap(filePath)


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?


Solution

  • Using a filestream will unlock the file once it has been read from and disposed:

    using (var fs = new System.IO.FileStream("c:\\path to file.bmp", System.IO.FileMode.Open))
    {
        var bmp = new Bitmap(fs);
        pct.Image = (Bitmap) bmp.Clone();
    }
    

    Edit: Updated to allow the original bitmap to be disposed, and allow the FileStream to be closed.

    THIS ANSWER IS NOT SAFE - See comments, and see discussion in net_prog's answer. The Edit to use Clone does not make it any safer - Clone clones all fields, including the filestream reference, which in certain circumstances will cause a problem.