【问题标题】:skipping files while deleting that are currently in use在删除当前正在使用的文件时跳过文件
【发布时间】:2022-07-26 22:18:40
【问题描述】:

我尝试制作一个临时清洁器和它自己工作的程序,但是我如何编写它跳过当前正在使用的文件的程序?

这是我使用的脚本

System.IO.DirectoryInfo di = new DirectoryInfo(path);

    foreach (FileInfo file in di.GetFiles())
    {
        file.Delete(); 
    }
    foreach (DirectoryInfo dir in di.GetDirectories())
    {
        dir.Delete(true); 
    }

【问题讨论】:

标签: c# visual-studio-code


【解决方案1】:
protected virtual bool IsFileLocked(FileInfo file)
{
    try
    {
        using(FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None))
        {
            stream.Close();
        }
    }
    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;
    }

    //file is not locked
    return false;
}

原帖:Is there a way to check if a file is in use?

【讨论】:

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