Displaying an Image Without Locking its File

July 5, 2010 | By

The PictureBox control is one of the most used controls in Windows Forms applications. And sometimes you might want to delete the image file that is displayed on it. Doing so with an image displayed using the Image.FromFile function will result in a file locked exception. And file will stay locked until the program exits, even if you set the variable to null.

The best solution to this problem is to load the file as stream using the Image.FromStream function. The following code is an example of how to do this.

Filed in: WinForms | Tags: ,

Comments (4)

Links to this Post

  1. DotNetShoutout | July 21, 2010
  1. Luc Pattyn

    Hi,

    I am aware using Image.FromStream() seems to solve the file-locked problem, however the MSDN documentation (http://msdn.microsoft.com/en-us/library/93z9ee4x.aspx) clearly says the stream should remain open as long as the Image exists; I’m afraid that implies the file, while not locked, should remain accessible.

    To be absolutely safe, I think one should read the file into a MemoryStream, then use Image.FromStream() from there.

    Cheers.

  2. Luc thanks for the input. You’re right, the file should remain accessible, but in this case the buffer is the PictureBox control’s image property so you don’t need a MemoryStream object.

  3. John

    Once you close the stream, the image is no longer savable.