c# file path string comparison case insensitivity

北城余情 提交于 2019-12-30 23:37:49

问题


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.


回答1:


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)




回答2:


string path1 = "C:\\TEST";
string path2 = "c:\\test";

if(path1.ToLower() == path2.ToLower())
    MessageBox.Show("True");

Do you mean this or did i not get the question?




回答3:


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 does a useless memory allocation every time you compare something




回答4:


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


来源:https://stackoverflow.com/questions/26230962/c-sharp-file-path-string-comparison-case-insensitivity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!