如何检查2个DirectoryInfo对象是否指向同一目录?

tra*_*nmq 11 c# directory

我有2个DirectoryInfo对象,并想检查它们是否指向同一目录.除了比较他们的全名,还有其他更好的方法吗?请忽略链接的情况.

这就是我所拥有的.

DirectoryInfo di1 = new DirectoryInfo(@"c:\temp");
DirectoryInfo di2 = new DirectoryInfo(@"C:\TEMP");

if (di1.FullName.ToUpperInvariant() == di2.FullName.ToUpperInvariant())
{ // they are the same
   ...   
}
Run Code Online (Sandbox Code Playgroud)

谢谢.

cod*_*nix 6

在Linux下,您可以比较它们相同的两个文件的INode编号.但是在Windows下没有这样的概念,至少不是我所知道的.您需要使用p/invoke来解析链接(如果有的话).

比较字符串是你能做的最好的事情.请注意,使用String.Compare(str1,str2,StringComparison.InvariantCultureIgnoreCase)比您接近快一点.


Mat*_*ole 6

您可以改用Uri对象.但是,您的Uri对象必须指向这些目录中的"文件".该文件实际上不必存在.

    private void CompareStrings()
    {
        string path1 = @"c:\test\rootpath";
        string path2 = @"C:\TEST\..\TEST\ROOTPATH";
        string path3 = @"C:\TeSt\RoOtPaTh\";

        string file1 = Path.Combine(path1, "log.txt");
        string file2 = Path.Combine(path2, "log.txt");
        string file3 = Path.Combine(path3, "log.txt");

        Uri u1 = new Uri(file1);
        Uri u2 = new Uri(file2);
        Uri u3 = new Uri(file3);

        Trace.WriteLine(string.Format("u1 == u2 ? {0}", u1 == u2));
        Trace.WriteLine(string.Format("u2 == u3 ? {0}", u2 == u3));

    }
Run Code Online (Sandbox Code Playgroud)

这将打印出来:

u1 == u2 ? True
u2 == u3 ? True
Run Code Online (Sandbox Code Playgroud)


Goo*_*ide 6

从 netstandard2.1 开始,终于有了一种几乎方便且与平台无关的方法来检查这一点:Path.GetRelativePath()

var areEqual = Path.GetRelativePath(path1, path2) == ".";
Run Code Online (Sandbox Code Playgroud)

适用于绝对路径和相对路径。也能正确处理类似的情况foo/../foo/bar == foo/bar