【问题标题】:Deleting Files - Skip Files in Use删除文件 - 跳过正在使用的文件
【发布时间】:2018-11-18 14:26:37
【问题描述】:

我正在尝试删除目录中的文件,但在尝试删除当前正在使用的文件时出现错误。有没有办法跳过当前正在使用的文件并删除其余文件?谢谢。

foreach(var file in Directory.GetFiles(tempPath))
{
    File.Delete(file);
}

这是我目前的代码,不知道该怎么做。

【问题讨论】:

  • 我的意思是,代码不会删除正在使用的文件,所以这真的无关紧要。如果您不想显示错误,您可以尝试捕获在尝试删除正在使用的文件时引发的异常,但这并不重要。

标签: c# file directory


【解决方案1】:

你可以通过 try catch 来检查

private bool IsLocked(string filePath)
    {

        FileInfo f = new FileInfo(filePath);
        FileStream stream = null;

        try
        {
            stream = f.Open(FileMode.Open, FileAccess.Read, FileShare.None);
        }
        catch (IOException ex)
        {
            return true;
        }
        finally
        {
            if (stream != null)
                stream.Close();
        }
        return false;
    }


    public void RemoveFile(string folderPath)
    {
        foreach (var file in Directory.GetFiles(folderPath))
        {
            if (!IsLocked(file))
            {
                File.Delete(file);
            }
        }
    }

【讨论】:

    【解决方案2】:

    我认为更简单的方法是用 try-catch 块包围您的代码。像这样的:

    foreach(var file in Directory.GetFiles(tempPath))
    {
        try 
        {
            File.Delete(file);
        } 
        catch (Exception) 
        {
            //Decide what you want to do here, you can either 
            //ask user to retry if the file is in use
            //Or ignore the failure and continue, or...
        }          
    }
    

    【讨论】:

    • 我的脑子里好像把它复杂化了,谢谢你的帮助!
    【解决方案3】:

    将 File.Delete 包装在 try { } catch 块中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-26
      • 1970-01-01
      • 2012-05-17
      • 1970-01-01
      • 2018-04-05
      • 2012-05-21
      • 2020-02-18
      • 1970-01-01
      相关资源
      最近更新 更多