Reputation: 39
I have a datagridview with an image column on my form and I set its value to an image in some folder ..
Bitmap PicImage;
PicImage = new Bitmap(ImagePath);
Grid.Rows[i].Cells["ImageColumn"].Value = PicImage;
when I want to delete the row ,the image should be deleted too, but I get "the process cannot access the file..." message :
File.delete(ImagePath);
How can I solve it?
Upvotes: 0
Views: 594
Reputation: 139
The following code unlinked the datagridview from the image file.
Bitmap timage;
using (Bitmap tmpImage = new Bitmap(tname))
{
timage = new Bitmap(tmpImage.Width, tmpImage.Height, PixelFormat.Format32bppArgb);
using (Graphics gr = Graphics.FromImage(timage))
gr.DrawImage(tmpImage, new Rectangle(0, 0, timage.Width, timage.Height));
}
fileGridView.Rows[dgIndex].Cells["thumbNail"].Value = timage;
Upvotes: 0
Reputation: 5629
The cleanest method is to load it without any links to files or streams. If it's just for showing on a UI, the simplest way to do this without deep-cloning using LockBits
is simply to paint it on a new 32BPP ARGB image:
Bitmap image;
using (Bitmap tmpImage = new Bitmap(filepath))
{
image = new Bitmap(tmpImage.Width, tmpImage.Height, PixelFormat.Format32bppArgb);
using (Graphics gr = Graphics.FromImage(image))
gr.DrawImage(tmpImage, new Rectangle(0, 0, image.Width, image.Height));
}
// Bitmap "image" is now ready to use.
Upvotes: 0
Reputation: 1438
Use a file stream to unlock the file , so instead of:
PicImage = new Bitmap(ImagePath);
use:
using (var stream= new System.IO.FileStream(ImagePath, System.IO.FileMode.Open))
{
var bmp= new Bitmap(stream);
PicImage = (Bitmap) bmp.Clone();
}
Upvotes: 1