我想和
this question完全一样:
Windows file system is case insensitive. How,given a file/folder name (e.g. “somefile”),I get the actual name of that file/folder (e.g. it should return “SomeFile” if Explorer displays it so)?
但是我需要在.NET中执行,我想要完整的路径(D:/Temp/Foobar.xml而不只是Foobar.xml)。
我看到FileInfo类上的FullName没有做到这一点。
我似乎NTFS是不区分大小写的,不管你的输入是否正确,总是会输入正确的。
获取正确的路径名称的唯一方法似乎找到像John Sibly所建议的文件。
我创建了一个方法,它将采取路径(文件夹或文件)并返回正确的套件版本(对于整个路径)
public static string GetExactPathName(string pathName)
{
if (!(File.Exists(pathName) || Directory.Exists(pathName)))
return pathName;
var di = new DirectoryInfo(pathName);
if (di.Parent != null) {
return Path.Combine(
GetExactPathName(di.Parent.FullName),di.Parent.GetFileSystemInfos(di.Name)[0].Name);
} else {
return di.Name.toupper();
}
}
这里有一些在我的机器上工作的测试用例:
static void Main(string[] args)
{
string file1 = @"c:\documents and settings\administrator\ntuser.dat";
string file2 = @"c:\pagefile.sys";
string file3 = @"c:\windows\system32\cmd.exe";
string file4 = @"c:\program files\common files";
string file5 = @"ddd";
Console.WriteLine(GetExactPathName(file1));
Console.WriteLine(GetExactPathName(file2));
Console.WriteLine(GetExactPathName(file3));
Console.WriteLine(GetExactPathName(file4));
Console.WriteLine(GetExactPathName(file5));
Console.ReadLine();
}
如果该文件不存在,该方法将返回提供的值。
可能会有更快的方法(这使用递归),但我不知道是否有明显的方法来做到这一点。