Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open Image from file, then release lock?

I'm using the following line of code to open an Image from a file:

pictureBox1.Image = Image.FromFile("test.png"); 

I expect it to lock the file, load the image to memory, set pictureBox1.Image to the copy in memory, and release the lock. In reality, the lock won't go away until I Dispose() of the Image in memory. I can not release the lock on the file on the harddrive that I am no longer using until I get rid of the file in memory that I am using.
Microsoft's site mentions it in a C#-labeled article, but their solution is written in visual basic, which is useless to me.

In summary: I want to set pictureBox1.Image to the image stored in "test.png", then let the user edit or delete "test.png" or whatever.

like image 270
Eagle-Eye Avatar asked Jul 04 '11 21:07

Eagle-Eye


2 Answers

The approach with stream is not correct.

See here https://stackoverflow.com/a/8701748/355264

Correct code from above link:

Image img; using (var bmpTemp = new Bitmap("image_file_path")) {     img = new Bitmap(bmpTemp); } 
like image 168
net_prog Avatar answered Sep 20 '22 11:09

net_prog


Or better yet, use a using statement (the code below is otherwise copied from sylon's [deleted] post). This way if the Image.FromStream throws an exception, you can still be assured that the stream is immediately closed.

using (FileStream stream = new FileStream("test.png", FileMode.Open, FileAccess.Read)) {     pictureBox1.Image = Image.FromStream(stream); } 
like image 33
JoshL Avatar answered Sep 17 '22 11:09

JoshL