当逐个删除文件时,会生成错误,因为"进程无法访问文件",因为在尝试删除文件时,其他进程正在使用该文件
代码:有关删除文件的任何建议吗?
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意:图像将被加载到这样的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;
}
}
Run Code Online (Sandbox Code Playgroud)
您没有具体说明您要删除的文件,但从您的问题来看,这听起来就像您正在尝试删除您加载的图像文件.如果是这种情况,那么你就有问题了.Image.FromFile的文档说:
文件保持锁定状态,直到图像被丢弃.
如果您需要删除文件的能力,您需要在加载图像后复制图像,并在图像中使用该图像PictureBox.然后您可以处理加载的图像,从而解锁文件.