Dựa trên các giải pháp của this question, tôi đã viết đoạn code dưới đây là trường hợp nhạy cảm đối với các toàn bộ con đường ngoại trừ hệ Cửa sổ Drive:
static void Main(string[] args)
{
string file1 = @"D:\tESt\Test.txt";
string file2 = @"d:\Test\test.txt";
string file3 = @"d:\test\notexists.txt";
bool exists1 = Case_Sensitive_File_Exists(file1);
bool exists2 = Case_Sensitive_File_Exists(file2);
bool exists3 = Case_Sensitive_File_Exists(file3);
Console.WriteLine("\n\nPress any key...");
Console.ReadKey();
}
static bool Case_Sensitive_File_Exists(string filepath)
{
string physicalPath = GetWindowsPhysicalPath(filepath);
if (physicalPath == null) return false;
if (filepath != physicalPath) return false;
else return true;
}
tôi sao chép mã cho GetWindowsPhysicalPath(string path)
từ the question
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern uint GetLongPathName(string ShortPath, StringBuilder sb, int buffer);
[DllImport("kernel32.dll")]
static extern uint GetShortPathName(string longpath, StringBuilder sb, int buffer);
protected static string GetWindowsPhysicalPath(string path)
{
StringBuilder builder = new StringBuilder(255);
// names with long extension can cause the short name to be actually larger than
// the long name.
GetShortPathName(path, builder, builder.Capacity);
path = builder.ToString();
uint result = GetLongPathName(path, builder, builder.Capacity);
if (result > 0 && result < builder.Capacity)
{
//Success retrieved long file name
builder[0] = char.ToLower(builder[0]);
return builder.ToString(0, (int)result);
}
if (result > 0)
{
//Need more capacity in the buffer
//specified in the result variable
builder = new StringBuilder((int)result);
result = GetLongPathName(path, builder, builder.Capacity);
builder[0] = char.ToLower(builder[0]);
return builder.ToString(0, (int)result);
}
return null;
}
Lưu ý vấn đề duy nhất tôi tìm thấy với chức năng này là, các ký tự ổ đĩa dường như luôn luôn trong chữ thường. Ví dụ: đường dẫn vật lý trên Windows là: D:\Test\test.txt
, các GetWindowsPhysicalPath(string path)
hàm trả d:\Test\test.txt
Nguồn
2015-10-07 15:09:46
MSDN lưu ý rõ ràng điều này: "Thông số đường dẫn không phân biệt chữ hoa chữ thường.", Hãy xem http://msdn.microsoft.com/en-us/library/system.io.directory.exists.aspx – David
Tôi biết, đó là lý do tại sao tôi hỏi ... – theknut