C# Filepath Recasing

前端 未结 6 1625
青春惊慌失措
青春惊慌失措 2020-12-29 06:37

I\'m trying to write a static member function in C# or find one in the .NET Framework that will re-case a file path to what the filesystem specifies.

Example:

<
6条回答
  •  我在风中等你
    2020-12-29 07:01

    You'll want the system to find the file for you. I do this by pretending that I do not know the exact path, i.e. have the system search:

    var fileName = Path.GetFileName(filePath);
    var dir = Path.GetDirectoryName(filePath);
    var filePaths = Directory.GetFiles(dir, fileName, SearchOption.TopDirectoryOnly);
    var caseCorrectedFilePath = filePaths.FirstOrDefault();
    

    So we search in the directory, filtering on the exact file name and limiting the search to the current directory only (no recursion).

    This returns a string array containing either the single file path with correct casing (if the file exists) or nothing (if the file does not exist).

    One warning: You may need to disallow wildcards in the input path, because this approach accepts them and may find multiple files as a result.

    Edit

    The drive letter appears to still follow the casing that we provide. Also, this needs to be tested for UNC paths.

提交回复
热议问题