“尝试删除文件时,进程无法访问该文件,因为它正被另一个进程使用”

当逐个删除文件时,会生成错误,因为“进程无法访问文件”,因为在尝试删除文件时,其他进程正在使用该文件

代码:删除这样的文件的任何建议?

private void DeleteFilesFromDestination() { string consolidatedFolder = System.Configuration.ConfigurationManager.AppSettings["path"].ToString(); foreach (String file in ListBoxDeleteFiles.Items) { try { // delete each selected files from the specified TargetFolder if (System.IO.File.Exists(consolidatedFolder + @"\" + System.IO.Path.GetFileName(file))) { proc.WaitForExit(); System.IO.File.Delete(consolidatedFolder + @"\" + System.IO.Path.GetFileName(file)); } } catch (Exception ex) { MessageBox.Show("Error Could not Delete file from disk " + ex.Message, "Shipment Instruction", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } } 

注意:图像将被加载到这样的flowlayout面板

  //Open the files to see private void ListBoxSourceFiles_Click(object sender, EventArgs e) { try { if (ListBoxSourceFiles.SelectedItem != null || !ListBoxSourceFiles.SelectedItem.Equals(string.Empty)) { //MessageBox.Show("Selected " + ListBoxSourceFiles.SelectedItem); PictureBox pb = new PictureBox(); Image loadedImage = null; loadedImage = Image.FromFile(ListBoxSourceFiles.SelectedItem.ToString()); pb.Height = loadedImage.Height; pb.Width = loadedImage.Width; pb.Image = loadedImage; flowLayoutPanel1.Controls.Clear(); flowLayoutPanel1.Controls.Add(pb); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Ship Instruction", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } } 

您没有具体说明您要删除的文件,但从您的问题来看,这听起来就像您正在尝试删除您加载的图像文件。 如果是这样的话,那你就有问题了。 Image.FromFile的文档说:

文件保持锁定状态,直到图像被丢弃。

如果您需要删除文件,则需要在加载图像后复制图像,并在PictureBox使用该图像。 然后您可以处理加载的图像,从而解锁文件。

当被另一个进程锁定时,您将无法删除任何文件。

首先,您必须找出锁定文件的进程。
这可以通过SysInternals ProcessExplorer实现。 使用“查找句柄或DLL”function。

如果文件正在使用中,则无法将其删除。 但是,如果由于某种原因确实要删除它并且您无法停止锁定文件的进程(例如卸载应用程序时),则可以在下次重新启动操作系统时安排删除文件。 在任何进程能够锁定文件之前执行这些计划的删除。

您必须使用null新文件名和标志MOVEFILE_DELAY_UNTIL_REBOOT来使用MoveFileEx Windows API。 C#中的Stack Overflow问题“MoveFile”函数的回答(重启后删除文件)C#中解释了如何从C#执行此操作。

 pb.Image.Dispose(); pb.Dispose(); 

经过上述步骤后,t​​ou可以再次使用图片