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

2023-11-30

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

代码:对于删除这样的文件有什么建议吗?

      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 的文档 says:

文件将保持锁定状态,直到图像被处理为止。

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐