C# Filepath Recasing

前端 未结 6 1222
青春惊慌失措
青春惊慌失措 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:03

    The answer by @Ants above should absolutely get credit as the accepted answer. However, I refactored it a bit to my purposes. The approach is packaged as extension methods for FileInfo and DirectoryInfo, and return corrected ones as well.

    public static DirectoryInfo GetProperCasedDirectoryInfo(this DirectoryInfo dirInfo)
    {
        // Inspired by http://stackoverflow.com/a/479198/244342
    
        if (!dirInfo.Exists)
        {
            // Will not be able to match filesystem
            return dirInfo;
        }
    
        DirectoryInfo parentDirInfo = dirInfo.Parent;
        if (parentDirInfo == null)
        {
            return dirInfo;
        }
        else
        {
            return parentDirInfo.GetProperCasedDirectoryInfo().GetDirectories(dirInfo.Name)[0];
        }
    }
    
    public static FileInfo GetProperCasedFileInfo(this FileInfo fileInfo)
    {
        // Inspired by http://stackoverflow.com/a/479198/244342
    
        if (!fileInfo.Exists)
        {
            // Will not be able to match filesystem
            return fileInfo;
        }
    
        return fileInfo.Directory.GetProperCasedDirectoryInfo().GetFiles(fileInfo.Name)[0];
    }
    

    I've been banging my head over some case-inconsistency issues with FileInfo. In order to ensure robustness, I convert to all caps when doing comparison or storage of the paths. To clarify the intent of the code, I also have these extension methods:

    public static string GetPathForKey(this FileInfo File)
    {
        return File.FullName.ToUpperInvariant();
    }
    
    public static string GetDirectoryForKey(this FileInfo File)
    {
        return File.DirectoryName.ToUpperInvariant();
    }
    

提交回复
热议问题