Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Picturebox keeping 'hold' of image file

Status
Not open for further replies.

emblewembl

Programmer
May 16, 2002
171
GB
I have a windows form which shows a list of images in pictureBoxes on a panel on 'tabPage1' using this code:

Code:
PictureBox pb = new PictureBox();
pb.Image = Image.FromFile(fileName);
pb.BorderStyle = BorderStyle.FixedSingle;
pb.BackColor = Color.White;
pb.Name = "pbI" + addimgCount;
pb.Width = 125;
pb.Height = 130;
pb.SizeMode = PictureBoxSizeMode.CenterImage;

I then go to 'tabPage2' and can edit some of these images - once i have edited the selected image the changes are saved but I get this error message:

Code:
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll

Additional information: The process cannot access the file "c:\Documents and Settings\E\My Documents\Visual Studio Projects\jS\ExImgs\Jpg\haydo\141001.jpg" because it is being used by another process.

This suggests to me that I am not clearing the picture box on tabPage1 properly or something as it seems to be still in use. When I leave tabPage1 I 'clean up' the panel using this code:

Code:
p.Controls.Clear();

but I am not sure how to clean up the picturebox and 'release' the image file. Can anyone help?!

i love chocolate
 
When you say Image.FromFile() you are opening the file and it remains open. when you then try to open it again for editing, you are trying to access an already open file.

Try editing the same instance of the image, or Dispose the Image or the Picturebox.

The other option is to store the image files in the project as Embedded resources. This way you can make individual instances of the image multiple times.
 
Thanks for the help but I have just replaced all Image.FromFile(fileName) references to:

Code:
FileStream fs = new FileStream(fileName,FileMode.Open, FileAccess.Read);
pb.Image = Image.FromStream(fs);

... and I'm still getting the same problem. Any other thoughts????

i love chocolate
 
Try

FileStream fs = new FileStream(fileName,FileMode.Open, FileAccess.Read);
pb.Image = Image.FromStream(fs);

fs.Close();
 
Thank you everyone, I have now used fs.close() after each reference to the fileStream and the error has gone!! :)

i love chocolate
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top