Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# file path string comparison case insensitivity

I would like to compare two strings containing file paths in c#.

However, since in ntfs the default is to use case insensitive paths, I would like the string comparison to be case insensitive in the same way.

However I can't seem to find any information on how ntfs actually implements its case insensitivity. What I would like to know is how to perform a case insensitive comparison of strings using the same casing rules that ntfs uses for file paths.

like image 758
Cedric Mamo Avatar asked Feb 11 '23 20:02

Cedric Mamo


2 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 combination such as "å" can appear, ordinal comparisons still offer the most transparent and fitting behavior.

Therefore it's simply:

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

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

like image 87
Lucas Trzesniewski Avatar answered Feb 15 '23 11:02

Lucas Trzesniewski


While comparison of paths the path's separator direction is also very important. For instance:

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

isEqual will be false.

Therefore needs to fix paths first:

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

Whereas this expression will be true:

bool isEqual = String.Equals(FixPath("myFolder\myFile.xaml"), FixPath("myFolder/myFile.xaml"), StringComparison.OrdinalIgnoreCase);
like image 32
Mr.B Avatar answered Feb 15 '23 09:02

Mr.B