Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verifying path equality with .Net

Tags:

c#

.net

path

People also ask

What is path in c#?

C# path class comes under System.IO namespace and System. Runtime. dll assembly. This class is used to perform operations on string instances that have file path or directory path information. A path is a string that holds the location of the file or directory and it can be an absolute or relative location.

What is the system io path?

Remarks. A path is a string that provides the location of a file or directory. A path does not necessarily point to a location on disk; for example, a path might map to a location in memory or on a device. The exact format of a path is determined by the current platform.


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.


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

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.


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
}