FileInfo是DirectoryInfo的后代

时间:2014-09-24 09:05:07

标签: c# .net fileinfo directoryinfo

如何检查FileInfo对象是否是DirectoryInfo的后代?

public bool IsFileDescendantOfDirectory(
    FileInfo fileInfo,
    DirectoryInfo directoryInfo)
{

}

6 个答案:

答案 0 :(得分:5)

你可以走上父目录:

public static bool IsFileDescendantOfDirectory(FileInfo fileInfo, DirectoryInfo directoryInfo)
{
    // https://connect.microsoft.com/VisualStudio/feedback/details/777308/inconsistent-behavior-of-fullname-when-provided-path-ends-with-a-backslash
    string path = directoryInfo.FullName.TrimEnd(Path.DirectorySeparatorChar);
    DirectoryInfo dir = fileInfo.Directory;
    while (dir != null)
    {
        if (dir.FullName.TrimEnd(Path.DirectorySeparatorChar).Equals(path, StringComparison.OrdinalIgnoreCase))
            return true;
        dir = dir.Parent;
    }
    return false;
}

有趣的是,您必须比较FullNameDirectoryInfo.Equals无法正常工作,因为它使用的Object.Equals只是比较引用。

答案 1 :(得分:2)

您可以检查文件的父级,直到它到达匹配的目录。这比在目录中搜索文件更快:

public bool IsFileDescendantOfDirectory(DirectoryInfo directoryInfo, FileInfo fileInfo)
{
    DirectoryInfo d = fileInfo.Directory;
    do
    {
        if (d.FullName.Equals(directoryInfo.FullName, StringComparison.OrdinalIgnoreCase))
        {
            return true;
        }

        d = d.Parent;
    }
    while(d != null);

    return false;
}

答案 2 :(得分:1)

在与Tim Schmelter进行一些反复讨论之后,我非常确定以下方法可用于确定FileInfo路径是否位于DirectoryInfo路径下:

public static bool IsFileBelowDirectory(FileInfo fileInfo, DirectoryInfo directoryInfo)
{
    var separator = Path.DirectorySeparatorChar.ToString();
    var directoryPath = string.Format("{0}{1}"
    , directoryInfo.FullName
    , directoryInfo.FullName.EndsWith(separator) ? "": separator);

    return fileInfo.FullName.StartsWith(directoryPath, StringComparison.OrdinalIgnoreCase);
}

有趣的是,您不需要走上目录来检查每个级别的eaqulity。当文件显然不在目录中时,这节省了一些时间;例如,对于目录C:\this\is\a\path\that\is\long而言,文件C:\this\is\a\path\that\is\also\long.txt走上目录会浪费检查,因为差异在路径的末尾。

答案 3 :(得分:0)

如果你想查找名字,这将是一个简单的解决方案:

Directory
.EnumerateFiles(di.FullName, *.*, SearchOption.AllDirectories)
.Any(x => x == fileInfo.FullName);

答案 4 :(得分:0)

FileInfo通过其Directory属性提供DirectoryInfo,DirectoryInfo提供Parent属性。所以只是;

DirectoryInfo fileOwner = myFileInfo.Directory;
do
{
   if(fileOwner == mySampleDirectory) Debug.WriteLine("Yes !");
   fileOwner = fileOwner.Parent;
} 
while(fileOwner != null)

答案 5 :(得分:-1)

这就够了:

    public static bool IsDirectoryParent(DirectoryInfo directoryInfo, DirectoryInfo parentInfo)
    {
        if (!directoryInfo.Name.StartsWith(parentInfo.FullName))
            return false;
        return directoryInfo.FullName == parentInfo.FullName 
            || IsDirectoryParent(directoryInfo.Parent, parentInfo);
    }

    public bool IsFileParent(FileInfo fileInfo, DirectoryInfo directoryInfo)
    {
        return IsDirectoryParent(fileInfo.Directory, directoryInfo);
    }