10

Possible Duplicate:
How to check whether 2 DirectoryInfo objects are pointing to the same directory?

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 
}

Whilst debugging, I can examine the values in each and they ARE equal. So i'm guessing this is another byval byref misunderstanding... Please someone, how do I compare these two things?

4

4 回答 4

8

我相信你想这样做:

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 
}

............

在您的示例中,您正在比较 2 个不同的对象,这就是它们不相等的原因。我相信您需要比较路径,因此请使用上面的代码。

于 2010-07-01T04:19:13.313 回答
7

我在 Google 上搜索了“DirectoryInfo 相等性”,发现了几个很好的结果,包括 StackOverflow 上的一个(如何检查 2 个 DirectoryInfo 对象是否指向同一个目录?

如果两个Directory.FullNames 匹配,那么你知道它们相同的,但如果它们不匹配,你仍然不知道多少。两个不同的字符串可以引用磁盘上的同一位置,存在短名称、链接和连接以及许多其他原因。

如果您指望确定两个字符串不在同一个位置,并且安全受到威胁,那么您很可能会产生安全漏洞。小心行事。

于 2010-07-01T04:30:06.207 回答
2

正如 Jaroslav Jandek 所说(对不起,我无法发表评论,没有足够的声誉)

因为它比较这两个实例,而不是它们的值(两个引用)。

实际上,对于许多其他情况来说也是如此!例如

IPAddress ip1 = IPAddress.Parse("192.168.0.1");
IPAddress ip2 = IPAddress.Parse("192.168.0.1");

两个 IP 地址代表相同的地址,但您有两个不同的 IPAddress 类实例。所以当然 "ip1 == ip2" 和 "ip1.Equals(ip2)" 都是假的,因为它们不指向同一个对象。

现在,如果您检查“ip1.Address == ip2.Address”,结果将为真,因为 IPAddress.Address 是“long”,因此您正在比较 2 种值类型。请注意,即使字符串是引用类型而不是值类型,“ip1.ToString() == ip2.ToString()”也将成立(但字符串确实很特殊)。

所以确实在你的情况下你想比较 FullName 属性(它是一个字符串,所以没问题)。

你说

是否仅通过使用属性,即 .FullName 属性来比较值而不是实例?

实际上它更多地与属性是值类型还是引用类型有关。同样在比较引用类型时,在大多数情况下,比较将是它们是否指向同一个对象,但可以覆盖方法或创建运算符,以便对对象的内容进行比较(再次就像 Jaroslav Jandek已经指出)。

高温高压

于 2010-07-01T10:51:58.220 回答
1

因为它比较这两个实例,而不是它们的值(两个引用)。

于 2010-07-01T04:20:41.063 回答