I'm checking 2 program config file paths from the registry. Sometimes one gets stored with a lowercase c, the other with an uppercase C which then doesn't work with a simple string comparison.
What I want to accomplish is basically that
"C:\MyPath\MyConfig.json" == "c:\MyPath\MyConfig.json"
But
"C:\MyPath\myconfig.json" != "C:\MyPath\MyConfig.json"
//Edit: I just noticed windows is not case sensitive at all, so latter codeblock is not even required. Sorry, i should have checked that in first place, but i always thought windows is case sensitive in paths, but it's indeed not it seems.
Is there something like Path.Compare(p1, p2)
or is the only way to do that manually?
You can use String.Equals()
to compare two pathes (strings).
The following returns true
:
var equal = String.Equals(@"C:\MyPath\MyConfig.json", @"c:\MyPath\MyConfig.json", StringComparison.OrdinalIgnoreCase); //or StringComparison.InvariantCultureIgnoreCase
UPDATE (after question update)
You should compare root and rest part of string:
var path1 = @"C:\MyPath\MyConfig.json";
var path2 = @"c:\MyPath\myConfig.json";
var rootEqual = String.Equals(Path.GetPathRoot(path1), Path.GetPathRoot(path2), StringComparison.OrdinalIgnoreCase); // true
var withoutRootEqual = String.Equals(path1.Substring(Path.GetPathRoot(path1).Length), path2.Substring(Path.GetPathRoot(path2).Length)); //false
var equal = rootEqual && withoutRootEqual;
Using this approach the results are:
"C:\MyPath\MyConfig.json" && "C:\MyPath\MyConfig.json" -> true
"C:\MyPath\MyConfig.json" && "c:\MyPath\MyConfig.json" -> true
"C:\MyPath\MyConfig.json" && "C:\MyPath\myConfig.json" -> false
"C:\MyPath\MyConfig.json" && "c:\MyPath\myConfig.json" -> false
Note: this will work on Windows only because root in Linux is different, but needed result can be achieved by the similar way.