C# 如何持续检查文件是否被删除以及是否被删除';无法删除,请重试

C# 如何持续检查文件是否被删除以及是否被删除';无法删除,请重试,c#,file,C#,File,在我当前的项目中,我面临随机错误,抱怨有问题的文件正被其他进程使用 有时它动作很快,一切都很好,有时它不起作用,不断地给我错误 另一个进程正在使用该文件 所以我想我把delete方法放在一个try catch中,在catch中我有一个循环,可以尝试删除这个文件,或者更好:解锁它,让它准备被删除 我不知道在这个循环中是否会出现另一个异常,以及如何管理它。如何找到将该进程与文件分离并准备删除的解决方案 更新 这是我目前的代码: private void Test(string imagePath)

在我当前的项目中,我面临随机错误,抱怨有问题的文件正被其他进程使用

有时它动作很快,一切都很好,有时它不起作用,不断地给我错误

另一个进程正在使用该文件

所以我想我把delete方法放在一个
try catch
中,在catch中我有一个循环,可以尝试删除这个文件,或者更好:解锁它,让它准备被删除

我不知道在这个循环中是否会出现另一个异常,以及如何管理它。如何找到将该进程与文件分离并准备删除的解决方案

更新 这是我目前的代码:

 private void Test(string imagePath)
 {
        try
        {
            if (File.Exists(imagePath))
            {
                pictureBoxExistingPicture.Visible = true;
                labelnew.Visible = true;
                labelold.Visible = true;
                pictureBoxExistingPicture.Image = ImageUtility.SafeLoadImage(imagePath);

                if (MessageBox.Show("Do you want to overwrite the existing image?", "warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes)
                {
                    pictureBoxExistingPicture.Image = Properties.Resources._default;//restore default

                    while (true)
                    {
                        try
                        {
                            File.Delete(imagePath);
                            break;
                        }
                        catch (Exception)
                        {
                        }
                    }

                    pictureBoxHonarjo.Image.Save(imagePath);
                }
                else
                {
                    pictureBoxHonarjo.Image = ImageUtility.SafeLoadImage(imagePath);//restore original image
                }

                pictureBoxExistingPicture.Visible = false;
                labelnew.Visible = false;
                labelold.Visible = false;
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
在当前的主题背景下,我需要说,如果用户希望替换图像,应该完成,并且不应该花费很长时间,也不应该失败。因此,基本上,当有人试图更改图片时,必须在很短的时间内更改

对于
SafeLoadImage
功能,以下是我的实现:

public class ImageUtility
{
   public static byte[] ImageToBytes(string FilePath, int FileLength)
   {
      FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
      BinaryReader breader = new BinaryReader(fileStream);
      return breader.ReadBytes(FileLength);
    }

    public static Image SafeLoadImage(string imagePath)
    {
        byte[] image_byte;
        Image image;
        FileInfo fileinfo = new FileInfo(imagePath);
        image_byte = ImageUtility.ImageToBytes(imagePath, (int)fileinfo.Length);
        image = ImageUtility.BytesToImage(image_byte);
        return image;
    }
}

因此,您有一些伪代码,例如:

success = false
while not success
..try
..  delete file
..  success = true
..catch
..  wait a second
while end
你可以添加一个重试计数器,这样它就不会无休止地循环等等。如果运气好的话,你可以猜到它在哪里

我故意不包含代码,因为您没有提供自己的代码,而是提供了一个要尝试的模板

因此,您有一些伪代码,例如:

success = false
while not success
..try
..  delete file
..  success = true
..catch
..  wait a second
while end
你可以添加一个重试计数器,这样它就不会无休止地循环等等。如果运气好的话,你可以猜到它在哪里


我故意不包括代码,因为您没有提供自己的代码,但给了您一个要尝试的东西的模板

这里有一个尝试删除文件的循环:

protected virtual bool IsFileLocked(FileInfo file) 
{ FileStream=null

try 
{ 
    stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); 
} 
catch (IOException) 
{ 
    //the file is unavailable because it is: 
    //still being written to 
    //or being processed by another thread 
    //or does not exist (has already been processed) 
    return true; 
} 
finally 
{ 
    if (stream != null) 
        stream.Close(); 
} 

//file is not locked 
return false; 
}


您还可以使用Process explorer了解哪个进程访问文件

这里有一个尝试删除文件的循环:

protected virtual bool IsFileLocked(FileInfo file) 
{ FileStream=null

try 
{ 
    stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); 
} 
catch (IOException) 
{ 
    //the file is unavailable because it is: 
    //still being written to 
    //or being processed by another thread 
    //or does not exist (has already been processed) 
    return true; 
} 
finally 
{ 
    if (stream != null) 
        stream.Close(); 
} 

//file is not locked 
return false; 
}


您还可以使用Process explorer了解哪个进程访问文件

ImageUtility。ImageToBytes完成后不会处理文件流

是这个锁定了文件吗

public static byte[] ImageToBytes(string FilePath, int FileLength) 
{ 
    FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read); 
    BinaryReader breader = new BinaryReader(fileStream); 
    return breader.ReadBytes(FileLength); 
}
考虑
using
语句,它将在执行退出代码块后释放资源(它包装IDisposable并为您调用dispose方法):

这可能是文件被锁定的原因


当然,如果其他人正在锁定您的文件,那么这可能是无用的:)但我怀疑这些是您创建/正在处理的图像文件

是这个锁定了文件吗

public static byte[] ImageToBytes(string FilePath, int FileLength) 
{ 
    FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read); 
    BinaryReader breader = new BinaryReader(fileStream); 
    return breader.ReadBytes(FileLength); 
}
考虑
using
语句,它将在执行退出代码块后释放资源(它包装IDisposable并为您调用dispose方法):

这可能是文件被锁定的原因


当然,如果其他人正在锁定您的文件,那么这可能没用:)但我怀疑这些是您创建/正在处理的图像文件

我的MessageBox简单解决方案:

bool deleted= false;
while(!deleted)
{
 try
  {
    File.Delete("path to file");                                 
    deleted = true;
  }
 catch 
  {
    MessageBox.Show("You can't delete file. Close file and press 'OK'");
    deleted = false; 
  }
}

我的MessageBox简单解决方案:

bool deleted= false;
while(!deleted)
{
 try
  {
    File.Delete("path to file");                                 
    deleted = true;
  }
 catch 
  {
    MessageBox.Show("You can't delete file. Close file and press 'OK'");
    deleted = false; 
  }
}

try catch
块放入循环中,如果成功,则将
break
。我认为您需要找出文件被锁定的原因。它可能会被锁定,原因很好。使用此选项可帮助找出锁定文件的进程@hmjd:谢谢,但这不是一个好的解决方案,现在我处于一个无限循环中,我不知道它什么时候结束!贾斯汀·哈维:我不知道我该如何处理这个问题?我在处理图片框,最有可能的过程是使用我的文件是我的项目本身,问题是我不知道它的哪个部分在使用它!我认为问题在于您没有释放ImageUtility中的文件锁(您需要关闭/处置读卡器)。检查我的答案,看看是否解决了你的问题,并考虑使用< <代码>使用< /Cult>块,当目标类型实现IDISPASABLE,放置<代码>尝试catch < /Cord>块内的循环和<代码>破解< /代码>如果成功。我想你需要弄清楚为什么文件被锁定。它可能会被锁定,原因很好。使用此选项可帮助找出锁定文件的进程@hmjd:谢谢,但这不是一个好的解决方案,现在我处于一个无限循环中,我不知道它什么时候结束!贾斯汀·哈维:我不知道我该如何处理这个问题?我在处理图片框,最有可能的过程是使用我的文件是我的项目本身,问题是我不知道它的哪个部分在使用它!我认为问题在于您没有释放ImageUtility中的文件锁(您需要关闭/处置读卡器)。检查我的答案,看看这是否解决了你的问题,当目标类型实现IDISPOSSABLE感谢你时,考虑使用<代码>使用< /代码>块。但它与第一条评论所建议的、目前正在应用程序中使用的相同场景并没有太大区别。我需要在运行时确定问题并消除它。虽然您的解决方案最终会起作用,但如果其他进程正在使用该文件,则尝试删除该文件需要时间。如果有人退出,我需要一个更快的方法来解决这个问题。谢谢。但它与第一条评论所建议的、目前正在应用程序中使用的相同场景并没有太大区别。我需要在运行时确定问题并消除它。虽然您的解决方案最终会起作用,但如果其他进程正在使用该文件,则尝试删除该文件需要时间。如果有人退出,我需要一个更快的方法来解决这个问题。谢谢。这似乎是原因,在做了你的建议后,它现在可以完美地工作:)谢谢。这似乎是原因,在做了你的建议后,它现在可以完美地工作:)