TBoy3
TBoy3

Reputation: 73

Can't delete file after drag drop

I'm moving a picture from explore to a win form. That works fine. After i have moved the picture i want to delete it in the folder, but that don't work. I'm getting the error that the file is in use in the winform.

I have tried with:

File.Delete(files[0])
files = null
img = null
img.Dispose()

But I still can't delete or move the file.

private void frmADManager_DragDrop(object sender, DragEventArgs e)
    {
        try
        {
            int x = PointToClient(new Point(e.X, e.Y)).X;

            int y = PointToClient(new Point(e.X, e.Y)).Y;

            if (x >= pbUser.Location.X && x <= pbUser.Location.X + pbUser.Width && y >= pbUser.Location.Y && y <= pbUser.Location.Y + pbUser.Height)

            {

                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                Image img = Image.FromFile(files[0]);
                if (img.Width == 648)
                { 
                    pbUser.Image = img;
                    SavePicture = true;
                    tsbtnSave.Enabled = true;
                    toolStrip1.Focus();
                    File.Delete(files[0]);
                    files = null;
                    img = null;
                    img.Dispose();                        
                }
                else

Upvotes: 0

Views: 336

Answers (1)

waka
waka

Reputation: 3417

You are trying to delete the image before you call img.Dispose(). Until the img is disposed it is still "in use", so just change the lines around:

if (img.Width == 648)
{ 
    pbUser.Image = img;
    SavePicture = true;
    tsbtnSave.Enabled = true;
    toolStrip1.Focus();
    img.Dispose();//you are disposing the img, no need to null it
    File.Delete(files[0]);
 }

Upvotes: 2

Related Questions