如果我有两个的DirectoryInfo
的对象,我怎么能对它们进行比较语义的平等?例如,下面的路径都应该被视为等于 C: TEMP
:
If I have two DirectoryInfo
objects, how can I compare them for semantic equality? For example, the following paths should all be considered equal to C:temp
:
C: TEMP
C: TEMP
C: TEMP
C: TEMP x .. .. TEMP
C:temp
C:temp
C:temp.
C:tempx....temp.
下面可能会或可能不等于 C: TEMP
:
The following may or may not be equal to C:temp
:
TEMP
如果当前的工作目录是驱动器 C:
温度
如果当前工作目录是 C:
C: TEMP
C: TEMP
temp
if the current working directory is on drive C:
temp
if the current working directory is C:
C:temp.
C:temp...
如果它要考虑当前的工作目录是很重要的,我能明白这一点我自己,所以这不是那么重要。小圆点是Windows剥离,因此这些路径确实应该是平等的 - 但他们没有在UNIX中剥离,所以下单我希望其他的结果。
If it's important to consider the current working directory, I can figure that out myself, so that's not that important. Trailing dots are stripped in windows, so those paths really should be equal - but they aren't stripped in unix, so under mono I'd expect other results.
区分大小写是可选的。该路径可能或可能不存在,并且用户可以或可以不具有权限的路径 - 我最好preFER一种快速可靠的方法,不需要任何的I / O(所以没有权限检查),但如果有一些内置的我很乐意与任何足够好太...
Case sensitivity is optional. The paths may or may not exist, and the user may or may not have permissions to the path - I'd prefer a fast robust method that doesn't require any I/O (so no permission checking), but if there's something built-in I'd be happy with anything "good enough" too...
推荐答案
从这个答案,这种方法可以处理一些边缘情况:
From this answer, this method can handle a few edge cases:
public static string NormalizePath(string path)
{
return Path.GetFullPath(new Uri(path).LocalPath)
.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)
.ToUpperInvariant();
}
在原来的答案更多细节。这样称呼它:
More details in the original answer. Call it like:
bool pathsEqual = NormalizePath(path1) == NormalizePath(path2);
应同时适用于文件和目录路径。
Should work for both file and directory paths.
相关推荐
最新文章