c# - 给定完整路径,检查路径是否是其他路径的子目录,否则

标签 c# .net directory

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

dir1.contains(dir2);

但如果目录具有相似的名称,例如 - c:\abcc:\abc1,这也会返回 true > 不是子目录,打赌返回真。一定有更好的方法。

最佳答案

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

或者在允许嵌套子目录的循环中,即 C:\foo\bar\bazC:\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;
}

关于c# - 给定完整路径,检查路径是否是其他路径的子目录,否则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5617320/

相关文章:

c# - C# 中哪些操作是原子操作?

c# - Dapper:将字符串转换为枚举

java - Netbeans 7.x : Maven creates my project in the wrong directory

.net - 不可见的标签页(标签控件)上的控件返回 Visible = false

c - 如何在Linux中查找执行文件?

linux - 监视目录列表的变化?

Visual Basic 中的 C# - 如何从并行数组中添加整数?

c# - 为什么我的菜单(无序列表)没有出现?包含 Menu.css

c# - IIS 7.5、Web 服务和 HTTP 405 错误

c# - 拆分包含空格的字符串,除非它们包含在 "quotes"中?