删除文件-跳过正在使用的文件

时间:2018-11-18 14:26:38

标签: c# file directory

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

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

那是我到目前为止的代码,不确定如何处理。

3 个答案:

答案 0 :(得分:3)

您可以尝试捕获

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);
            }
        }
    }

答案 1 :(得分: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...
    }          
}

答案 2 :(得分:0)

包装文件。在try {} catch块中删除