检查路径是否是其他路径的子目录

检查路径是否是其他路径的子目录

本文介绍了给定完整路径,检查路径是否是其他路径的子目录,否则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个字符串 - dir1 和 dir2,我需要检查一个是否是另一个的子目录.我尝试使用 contains 方法:

I have 2 strings - dir1 and dir2, and I need to check if one is sub-directory for other. I tried to go with Contains method:

dir1.contains(dir2);

但如果目录具有相似的名称,则也返回 true,例如 - c:abcc:abc1 不是子目录,下注返回 true.一定有更好的方法.

but that also returns true, if directories have similar names, for example - c:abc and c:abc1 are not sub-directories, bet returns true. There must be a better way.

推荐答案

DirectoryInfo di1 = new DirectoryInfo(dir1);
DirectoryInfo di2 = new DirectoryInfo(dir2);
bool isParent = di2.Parent.FullName == di1.FullName;

或者在循环中允许嵌套子目录,即C:fooarazC:foo的子目录:>

Or in a loop to allow for nested sub-directories, i.e. C:fooaraz is a sub directory of C:foo :

DirectoryInfo di1 = new DirectoryInfo(dir1);
DirectoryInfo di2 = new DirectoryInfo(dir2);
bool isParent = false;
while (di2.Parent != null)
{
    if (di2.Parent.FullName == di1.FullName)
    {
        isParent = true;
        break;
    }
    else di2 = di2.Parent;
}

这篇关于给定完整路径,检查路径是否是其他路径的子目录,否则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 17:20