2017-03-01 86 views
0

我正在將一張圖片從探索畫面移至勝出表格。這工作正常。我已經移動圖片後,我想刪除它在文件夾中,但不起作用。我收到文件在winform中使用的錯誤。拖放後無法刪除文件

我曾嘗試用:

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

但我還是不能刪除或移動文件。

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 
+0

如果您需要保留圖像中'pbUser'那麼你應該使用的源代碼的副本。 I.E .:'pbUser.Image =新的位圖(img);'。也請遵循@waka的回答。不要試圖使用'img.Clone()',因爲克隆還會引用源文件並阻止您刪除該文件。 – TnTinMn

回答

2

您正在嘗試刪除圖片,然後再致電img.Dispose()。直到IMG配置它仍然是「正在使用」,所以只是改變了線路周圍:

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]); 
} 
+0

如果我只使用Wakas的答案,我收到錯誤「在System.Drawing.dll中發生類型'System.ArgumentException'的未處理異常」如果我也使用TnTinMn中的answare,則在更改時發生錯誤「System.DirectoryServices .DirectoryServicesCOMException:發生約束違規。「 – TBoy3

+0

好吧,我將img.Dispose()移動到我提交了更改之後。這工作。感謝你們兩位的幫助。 – TBoy3