0

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.

Carlos Oliveira
  • 477
  • 6
  • 11
Mike_G
  • 16,237
  • 14
  • 70
  • 101
  • 1
    You don't dispose your bitmaps. – CodeCaster Jul 07 '14 at 15:39
  • That's fine, but how do I release the handle the app has on it? – Mike_G Jul 07 '14 at 15:39
  • 1
    By disposing the bitmaps. See for example [Free file locked by new Bitmap(filePath)](http://stackoverflow.com/questions/4803935/free-file-locked-by-new-bitmapfilepath). – CodeCaster Jul 07 '14 at 15:41
  • Yes, thanks. Tried that as the question mentioned. I removed it from the code since it didn't help. Maybe ill try it again. – Mike_G Jul 07 '14 at 15:47
  • `bm = new Bitmap(paths[0])` locks the file at `paths[0]` until you dispose the bitmap referenced by `bm`, there's little more to make of that. – CodeCaster Jul 07 '14 at 15:48

2 Answers2

1

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);
}
Bill Sambrone
  • 4,334
  • 4
  • 48
  • 70
0

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.

Mike_G
  • 16,237
  • 14
  • 70
  • 101