C # file path comparison string case insensitive

I would like to compare two lines containing file paths in C #.

However, since ntfs uses case-insensitive paths by default, I would like string comparisons to be case-insensitive in the same way.

However, I cannot find any information on how ntfs really implements its case sensitivity. I would like to know how to perform case-insensitive string comparisons using the same casing rules that ntfs uses for file paths.

+4
string c # case-insensitive ntfs
Oct 07 '14 at 7:41
source share
4 answers

From MSDN :

The string behavior of the file system, registry keys and values, and environment variables is best represented by StringComparison.OrdinalIgnoreCase .

and

When interpreting file names, cookies, or anything else where a “å” type combination may appear, ordinal comparisons still provide the most transparent and appropriate behavior.

Therefore it is simple:

 String.Equals(fileNameA, fileNameB, StringComparison.OrdinalIgnoreCase) 

(I always use the static Equals call in case the left operand is null )

+7
Oct 07 '14 at 7:47
source share
 string path1 = "C:\\TEST"; string path2 = "c:\\test"; if(path1.ToLower() == path2.ToLower()) MessageBox.Show("True"); 

Do you mean this or didn’t I get the question?

0
07 Oct '14 at 7:48
source share

I would go for

 string.Compare(path1, path2, true) == 0 

or if you want to specify cultures:

 string.Compare(path1, path2, true, CultureInfo.CurrentCulture) == 0 

using ToUpper makes useless memory allocation every time you compare something

0
Oct 07 '14 at 7:52
source share

When comparing paths, the path direction of the path separator is also very important. For example:

  bool isEqual = String.Equals("myFolder\myFile.xaml", "myFolder/myFile.xaml", StringComparison.OrdinalIgnoreCase); 

isEqual will be false .

Therefore, you must first correct the paths:

  private string FixPath(string path) { return path.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) .ToUpperInvariant(); } 

While this expression will be true :

 bool isEqual = String.Equals(FixPath("myFolder\myFile.xaml"), FixPath("myFolder/myFile.xaml"), StringComparison.OrdinalIgnoreCase); 
0
Aug 23 '16 at 13:05
source share



All Articles