How do I determine whether the filesystem is case-

2019-02-16 15:41发布

Does .net have a way to determine whether the local filesystem is case-sensitive?

9条回答
贪生不怕死
2楼-- · 2019-02-16 16:18

You can create a file in the temp folder (using lowercase filename), then check if the file exists (using uppercase filename), e.g:

string file = Path.GetTempPath() + Guid.NewGuid().ToString().ToLower();
File.CreateText(file).Close();
bool isCaseInsensitive = File.Exists(file.ToUpper());
File.Delete(file);
查看更多
疯言疯语
3楼-- · 2019-02-16 16:20

There is no such a function in the .NET Class Library.

You can, however, roll out your own: Try creating a file with a lowercase name and then try to open it with the upparcase version of its name. Probably it is possible to improve this method, but you get the idea.

EDIT: You could actually just take the first file in the root directory and then check if both filename.ToLower() and filename.ToUpper() exist. Unfortunately it is quite possible that both uppercase and lowercase variants of the same file exist, so you should compare the FileInfo.Name properties of both the lowercase and uppercase variants to see if they are indeed the same or not. This will not require writing to the disk.

Obviously, this will fail if there are no files at all on the volume. In this case, just fall back to the first option (see Martin's answer for the implementation).

查看更多
唯我独甜
4楼-- · 2019-02-16 16:24
/// <summary>
/// Check whether the operating system is case-sensitive.
/// For instance on Linux you can have two files/folders called
//// "test" and "TEST", but on Windows the two can not coexist.
/// This method does not extend to mounted filesystems, which might have different properties.
/// </summary>
/// <returns>true if the operating system is case-sensitive</returns>
public static bool IsFileSystemCaseSensitive()
{
    // Actually try.
    string file = Path.GetTempPath() + Guid.NewGuid().ToString().ToLower() + "test";
    File.CreateText(file).Close();
    bool result = ! File.Exists(file.ToUpper());
    File.Delete(file);

    return result;
}

Based on M4N's answer, with the following changes:

  • Static names so that we are sure it contains a letter and not only numbers.
  • Maybe more readable?
  • Wrapped in a method.
  • Documentation.

A better strategy would be to take a path as an argument, and create the file on the same filesystem, but writing there might have unexpected consequences.

查看更多
登录 后发表回答