Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET How to compare two Strings that represent filenames ignoring case correctly

Given that (at least on NTFS) the filesystem on Windows is case insensitive, I would like to compare String fileA to String fileB as such:

fileA.Equals(fileB, StringComparison.CurrentCultureIgnoreCase)

The question then becomes which culture I should use, does the default current (ui?) culture suffice? I can't seem to find any BCL methods for this purpose.

like image 356
Marcus Avatar asked Nov 18 '09 15:11

Marcus


People also ask

How do you compare two strings to ignore cases?

The equalsIgnoreCase() method compares two strings, ignoring lower case and upper case differences. This method returns true if the strings are equal, and false if not. Tip: Use the compareToIgnoreCase() method to compare two strings lexicographically, ignoring case differences.

Which string function is used to compare first n characters of two strings ignoring cases?

strcmpi() - Compare Strings Without Case Sensitivity #include <string. h> int strcmpi(const char *string1, const char *string2);


2 Answers

You should use StringComparison.OrdinalIgnoreCase, according to Best Practices for Using Strings in the .NET Framework.

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

If you use a culture for matching the strings, you may get in a sitation where for example the names "häl.gif" and "hal.gif" would be considered a match.

like image 194
Guffa Avatar answered Oct 02 '22 13:10

Guffa


This is not possible to do reliably.

Yes, the case conversion for the file system is case-insensitive.

But the case conversion table is stored on the file system itself (for NTFS), and it does change between versions (for instance the Vista case conversion table was brought to the Unicode 5 level, so Vista NTFS and XP NTFS have different case conversion rules).

And the thing that matters is the OS that formatted the file system, not the current OS.

Then you can run into all kind of problems with other file systems (Mac OS does some kind of Unicode normalization (not the standard one)), Linux does not do anything, but Samba (implementing the Windows file sharing protocol) does. And has other tables than Windows.

So what happens if I map a letter to a network disk shared by Linux or Mac OS?

In general you should never try to compare file names. If you want to know if it is there, try to access it.

like image 23
Mihai Nita Avatar answered Oct 02 '22 13:10

Mihai Nita