Reputation: 8003
I load an image into a picturebox:
myPictureBox.Image = Image.FromFile(strImageFile);
and works perfectly, but the image file is locked and I can't manage until my application is closed..
I need, from another window of the program, save a new image to reload when this child window is closed..
Upvotes: 2
Views: 3099
Reputation: 1
My experience shows that PictureBox.LoadAsync does NOT seem to lock the file. I was even able to delete such a file with IO.FileInfo.Delete while it was still showing in the PictureBox. I have not made systematic studies, but I recommend to give it a try.
Upvotes: 0
Reputation: 19106
As documented load the image from the file and assign a cloned instance to the picture box.
If you want to use the same image in multiple PictureBox controls, create a clone of the image for each PictureBox. Accessing the same image from multiple controls causes an exception to occur.
And to keep the file unlocked, just use it only for the clone time:
using ( var img = Image.FromFile( fileName ) )
{
pictureBox2.Image = (Image) img.Clone();
}
Upvotes: 1
Reputation: 1628
An easy approach is to copy the image from the file to a new Bitmap
and dispose the instance from the file after that. This is best done with a proper using construct:
using(var fromFile = Image.FromFile(strImageFile))
{
myPictureBox.Image = new Bitmap(fromFile);
}
Upvotes: 1
Reputation: 26876
Well, you can use Image.FromStream
instead Image.FromFile
and wrap stream you're reading from into using
to make sure it will be released after you've done reading.
using (var stream = File.Open(strImageFile, FileMode.Open))
{
myPictureBox.Image = Image.FromStream(stream);
}
Upvotes: 0
Reputation: 73492
Image.FromFile
will keep the File open which prevents access to the image file till the Image is disposed. If you want to release the lock, you need to keep the Image file in memory.
myPictureBox.Image = Image.FromStream(new MemoryStream(File.ReadAllBytes(strImageFile)));
Upvotes: 5