为什么这个DirectoryInfo比较不起作用?

bar*_*ron 7 c# comparison logic directoryinfo visual-studio

可能重复:
如何检查2个DirectoryInfo对象是否指向同一目录?

var dirUserSelected = new DirectoryInfo(Path.GetDirectoryName("SOME PATH"));
var dirWorkingFolder = new DirectoryInfo(Path.GetDirectoryName("SAME PATH AS ABOVE"));

if (dirUserSelected == dirWorkingFolder)
{ 
   //this is skipped 
}

if (dirUserSelected.Equals(dirWorkingFolder))
{ 
   //this is skipped 
}
Run Code Online (Sandbox Code Playgroud)

在调试时,我可以检查每个中的值,它们是相等的.所以我猜这是另一个byval byref误解......请有人,我该如何比较这两件事?

Inc*_*ito 9

我相信你想这样做:

var dirUserSelected = new DirectoryInfo(Path.GetDirectoryName(@"c:\some\path\"));
var dirWorkingFolder = new DirectoryInfo(Path.GetDirectoryName(@"c:\Some\PATH"));

if (dirUserSelected.FullName  == dirWorkingFolder.FullName )
{ // this will be skipped, 
  // since the first string contains an ending "\" and the other doesn't
  // and the casing in the second differs from the first
}

// to be sure all things are equal; 
// either build string like this (or strip last char if its a separator) 
// and compare without considering casing (or ToLower when constructing)
var strA = Path.Combine(dirUserSelected.Parent, dirUserSelected.Name);
var strB = Path.Combine(dirWorkingFolder.Parent, dirWorkingFolder.Name);
if (strA.Equals(strB, StringComparison.CurrentCultureIgnoreCase)
{ //this will not be skipped 
}

............
Run Code Online (Sandbox Code Playgroud)

在您的示例中,您正在比较两个不同的对象,这就是它们不相等的原因.我相信你需要比较Paths所以使用上面的代码.


Jay*_*uzi 5

我做了一个谷歌搜索"DirectoryInfo相等",并发现了几个很棒的结果,包括一个关于StackOverflow(如何检查2个DirectoryInfo对象是否指向同一目录?)

如果两个Directory.FullName匹配,那么你知道它们相同的,但是如果它们不匹配,你仍然不太了解.有短名称,链接和联结以及许多其他原因,两个不同的字符串可以引用磁盘上的相同位置.

如果您依赖于确定两个字符串不是同一个位置,并且安全性受到威胁,那么您可能会创建一个安全漏洞.小心翼翼.

  • 一些"愚弄"DirectoryInfo的方法:`subst`命令,`net use`命令或网络共享. (3认同)