繁体   English   中英

Directory.Exists 之后的 DirectoryNotFoundException

[英]DirectoryNotFoundException after Directory.Exists

怎么会出现以下语句:

if (Directory.Exists(outputDestination) 
    && new DirectoryInfo(outputDestination).GetFiles().Count() > 0)

抛出DirectoryNotFoundException :在调用 GetFiles() 之前,如果我检查目录存在,则找不到路径的一部分

下面如何声明:

 if (Directory.Exists(outputDestination) && new DirectoryInfo(outputDestination).GetFiles().Count() > 0) 

抛出DirectoryNotFoundException吗?

您的代码可以引发DirectoryNotFoundException因为您已经创建了TOCTOU错误

在软件开发中, 检查时间到使用时间 (TOCTTOU或TOCTOU,发音为“ tock too”)是一类软件错误,由系统在条件检查(例如安全凭证)和使用之间的更改引起。检查结果。 这是比赛条件的一个例子。

仅仅因为目录存在于对Directory.Exists()的调用中,并不意味着它仍然存在于对DirectoryInfo()的调用中。

对于跨驱动器卷的移动操作,我遇到了这个问题。 即使 OP 说他们的答案是竞争条件。 还有其他可能引发异常的原因,例如文件名太长。 根据文档

找不到文件或目录的一部分时抛出的异常。

当文件的一部分是关键时。 捕获中的检查将显示长文件名将给出DirectoryNotFoundException

try
{
    fromFile.CopyTo(toFile.FullName, toFile.Exists);
}
catch (DirectoryNotFoundException)
{
    // can occur for really long file names
    if (Math.Max(fromFile.FullName.Length, toFile.FullName.Length) >= 260)
    {
        try
        {
            // in 4.6.1 they added handling for long file names, but its weird
            string from = $"\\\\?\\{fromFile.FullName}";
            string to = $"\\\\?\\{toFile.FullName}";
            File.Copy(from, to, File.Exists(to));
            if (File.Exists(to))
            {
                File.Delete(from);
                Log("Success\n");
                continue;
            }
        }
        catch (DirectoryNotFoundException)
        {
            Log("Failed\n");
            continue;
        }
    }
    throw;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM