PictureBox help!
-
Ok, so I have a PictureBox on my form named pctInternet. It has the following code associated with it:
string imageLocation = @"C:\mypicture.jpg"; Bitmap bmp = new Bitmap(imageLocation); pctInternet.Image = bmp;
Now, I just want my PictureBox to display the picture and CLOSE the actual "mypicture.jpg" file, but for some reason whenever I try to delete the "mypicture.jpg" file while my app is running, it errors and says "File is in use." How do I fix this? What line of code am I missing? -
Ok, so I have a PictureBox on my form named pctInternet. It has the following code associated with it:
string imageLocation = @"C:\mypicture.jpg"; Bitmap bmp = new Bitmap(imageLocation); pctInternet.Image = bmp;
Now, I just want my PictureBox to display the picture and CLOSE the actual "mypicture.jpg" file, but for some reason whenever I try to delete the "mypicture.jpg" file while my app is running, it errors and says "File is in use." How do I fix this? What line of code am I missing?Because the file is in use. What you need to do is clonse the
Bitmap
and then dispose it:using (Bitmap bmp = new Bitmap(imageLocation))
{
pctInternet.Image = (Bitmap)bmp.Clone();
}It's good to use the
using
block statement forIDisposable
implementation because it ensures that objects are disposed even if an exception occurs (it compiles to a try-finally block). This posting is provided "AS IS" with no warranties, and confers no rights. Software Design Engineer Developer Division Sustained Engineering Microsoft [My Articles] [My Blog] -
Because the file is in use. What you need to do is clonse the
Bitmap
and then dispose it:using (Bitmap bmp = new Bitmap(imageLocation))
{
pctInternet.Image = (Bitmap)bmp.Clone();
}It's good to use the
using
block statement forIDisposable
implementation because it ensures that objects are disposed even if an exception occurs (it compiles to a try-finally block). This posting is provided "AS IS" with no warranties, and confers no rights. Software Design Engineer Developer Division Sustained Engineering Microsoft [My Articles] [My Blog]That doesn't work though. Another work around might be the following:
string loc = @"C:\\image1.gif"; using(Bitmap bmp = new Bitmap(loc)) { using(Graphics g = Graphics.FromHwnd(this.Handle)) { g.DrawImage(bmp, 5, 5); } }
- Nick Parker
My Blog | My Articles