Eamon Nerbonne Eamon Nerbonne - 3 months ago 9
C# Question

How can I compare (directory) paths in C#?

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\.



The following may or may not be equal to
C:\temp
:


  • \temp
    if the current working directory is on drive
    C:\

  • temp
    if the current working directory is
    C:\

  • C:\temp.

  • C:\temp...\



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.

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...

Answer

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.