C# &引用;该进程无法访问该文件,因为另一进程正在使用该文件;尝试删除文件时
在逐个删除文件时,会生成错误“进程无法访问文件”,因为在尝试删除文件时另一进程正在使用该文件” 代码:对删除这样的文件有什么建议吗C# &引用;该进程无法访问该文件,因为另一进程正在使用该文件;尝试删除文件时,c#,.net,C#,.net,在逐个删除文件时,会生成错误“进程无法访问文件”,因为在尝试删除文件时另一进程正在使用该文件” 代码:对删除这样的文件有什么建议吗 private void DeleteFilesFromDestination() { string consolidatedFolder = System.Configuration.ConfigurationManager.AppSettings["path"].ToString(); for
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;
}
}
当被另一个进程锁定时,您将无法删除任何文件 您首先必须找出哪个进程锁定文件。
这在ProcessExplorer中是可能的。使用“查找句柄或DLL”功能。如果文件正在使用,则无法删除它。但是,如果出于某种原因确实要删除该文件,并且无法停止锁定该文件的进程(如卸载应用程序时),则可以安排在下次重新启动操作系统时删除该文件。在任何进程能够锁定文件之前,都会执行这些计划的删除
您必须使用一个空的新文件名和标志
MOVEFILE\u DELAY\u直到重新启动
,来使用Windows API。如何从C#中删除,在对堆栈溢出问题的回答中进行了解释。您没有明确说明要删除的文件,但从您的问题中,听起来您好像要删除加载的图像文件。如果是这样,那么你就有问题了。报告说:
在释放图像之前,文件将保持锁定状态
如果您需要删除文件的功能,则需要在加载图像后复制该图像,并在PictureBox
中使用该图像。然后可以处理加载的图像,从而解锁文件
pb.Image.Dispose();
pb.Dispose();
完成上述步骤后,您可以再次使用picture您可以使用“Unlocker”之类的工具来确定是哪个进程锁定了文件。如果您自己打开文件(如果它们是组合框中的图像),您可以尝试先将文件复制到(内存)位图中,而不是直接从图像加载。只是一个想法,因此只是一个注释。检查文件是否在其他程序中保持打开状态。您可以尝试关闭所有实例,如果在多用户计算机上,请检查是否有其他用户正在访问它。然后再试一次。可能重复的