Verifying path equality with .Net

Although it's an old thread posting as i found one.

Using Path.GetFullpath I could solve my Issue eg.

Path.GetFullPath(path1).Equals(Path.GetFullPath(path2))

var path1 = Path.GetFullPath(@"c:\Some Dir\SOME FILE.XXX");
var path2 = Path.GetFullPath(@"C:\\\SOME DIR\subdir\..\some file.xxx");

// outputs true
Console.WriteLine("{0} == {1} ? {2}", path1, path2, string.Equals(path1, path2, StringComparison.OrdinalIgnoreCase));

Ignoring case is only a good idea on Windows. You can use FileInfo.FullName in a similar fashion, but Path will work with both files and directories.

Not sure about your second example.


I had this problem too, but I tried a different approach, using the Uri class. I found it to be very promising so far :)

var sourceUri = new Uri(sourcePath);
var targetUri = new Uri(targetPath);

if (string.Compare(sourceUri.AbsoluteUri, targetUri.AbsoluteUri, StringComparison.InvariantCultureIgnoreCase) != 0 
|| string.Compare(sourceUri.Host, targetUri.Host, StringComparison.InvariantCultureIgnoreCase) != 0)
            {
// this block evaluates if the source path and target path are NOT equal
}

Nice syntax with the use of extension methods

You can have a nice syntax like this:

string path1 = @"c:\Some Dir\SOME FILE.XXX";
string path2 = @"C:\\\SOME DIR\subdir\..\some file.xxx";

bool equals = path1.PathEquals(path2); // true

With the implementation of an extension method:

public static class StringExtensions {
    public static bool PathEquals(this string path1, string path2) {
        return Path.GetFullPath(path1)
            .Equals(Path.GetFullPath(path2), StringComparison.InvariantCultureIgnoreCase);
    }
}

Thanks to Kent Boogaart for the nice example paths.

Tags:

C#

.Net

Path