C# Filepath Recasing

前端 未结 6 1531
青春惊慌失措
青春惊慌失措 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条回答
  •  -上瘾入骨i
    2020-12-29 06:42

    This is a pretty simple implementation that assumes that the file and directories all exist and are accessible:

    static string GetProperDirectoryCapitalization(DirectoryInfo dirInfo)
    {
        DirectoryInfo parentDirInfo = dirInfo.Parent;
        if (null == parentDirInfo)
            return dirInfo.Name;
        return Path.Combine(GetProperDirectoryCapitalization(parentDirInfo),
                            parentDirInfo.GetDirectories(dirInfo.Name)[0].Name);
    }
    
    static string GetProperFilePathCapitalization(string filename)
    {
        FileInfo fileInfo = new FileInfo(filename);
        DirectoryInfo dirInfo = fileInfo.Directory;
        return Path.Combine(GetProperDirectoryCapitalization(dirInfo),
                            dirInfo.GetFiles(fileInfo.Name)[0].Name);
    }
    

    There is a bug with this, though: Relative paths are converted to absolute paths. Your original code above did the same, so I'm assuming that you do want this behavior.

提交回复
热议问题