Reputation: 16502
I am trying to delete an image once it has been dragged and dropped on to a windows form. Below is how I am handling the drag and drop:
private void OnDrop(object sender, DragEventArgs e)
{
var paths = (string[])e.Data.GetData(DataFormats.FileDrop);
Bitmap bm = new Bitmap(paths[0]);
var newPath = paths[0].Substring(paths[0].LastIndexOf("\\") + 1);
bm.Save(newPath);
pictureEdit1.Image = new Bitmap(newPath);
}
private void OnDragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.Copy;
}
}
If I try to delete the original image from Windows Explorer I get the "this file is in use" error. I have tried calling Dispose on bm
bitmap, but that does not seem to help.
edit: To clarify, when I was calling Dispose, I was calling it right after the bm.Save(newPath
section and still gives me the error mentioned.
Upvotes: 0
Views: 357
Reputation: 16502
This turned out to be a hiccup in VS. I re-added the Dispose
logic and got the same error. Finally I shut down VS and restarted it, tried again and it worked.
Upvotes: 0
Reputation: 4464
Try wrapping the bitmap in a using block like below.
private void OnDrop(object sender, DragEventArgs e)
{
var paths = (string[])e.Data.GetData(DataFormats.FileDrop);
using(var bm = new Bitmap(paths[0]))
{
var newPath = paths[0].Substring(paths[0].LastIndexOf("\\") + 1);
bm.Save(newPath);
}
// using block is all done, handle should be released. delete that bad boy.
File.Delete(paths[0]);
pictureEdit1.Image = new Bitmap(newPath);
}
Upvotes: 1