在Windows上获取实际的文件名(用适当的外壳)与.NET [英] Getting actual file name (with proper casing) on Windows with .NET

查看:123
本文介绍了在Windows上获取实际的文件名(用适当的外壳)与.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这样做完全一样的<一个href="http://stackoverflow.com/questions/74451/getting-actual-file-name-with-proper-casing-on-windows">this问题:

I want to do exactly the same as in this question:

Windows文件系统不区分大小写。怎么样,给定的文件/文件夹的名称(如somefile),我得到的文件/文件夹的实际名称(例如,它应该返回SomeFile如果资源管理器中显示它的话)?

Windows file system is case insensitive. How, given a file/folder name (e.g. "somefile"), I get the actual name of that file/folder (e.g. it should return "SomeFile" if Explorer displays it so)?

不过,我需要做的是在.NET和我想的完整路径( D:/Temp/Foobar.xml 而不仅仅是 Foobar的的.xml )。

But I need to do it in .NET and I want the full path (D:/Temp/Foobar.xml and not just Foobar.xml).

我看到全名的FileInfo 类并没有做的伎俩。

I see that FullName on the FileInfo class doesn't do the trick.

推荐答案

我看来,因为NTFS是不区分大小写,将一直工作,除非你输入正确不管名称是套管权利。

I seems that since NTFS is case insensitive it will always except your input correctly regardless if the name is cased right.

要得到正确的路径名的唯一方法似乎找到像约翰Sibly文件建议。

The only way to get the correct path name seems to find the file like John Sibly suggested.

我创建了一个方法,将采取的路径(文件夹或文件),并返回它的正确套管的版本:(整个路径)

I created a method that will take a path (folder or file) and return the correctly cased version of it: (for the entire path)

    public static string GetExactPathName(string pathName)
    {
        if (!(File.Exists(pathName) || Directory.Exists(pathName)))
            return pathName;

        var di = new DirectoryInfo(pathName);

        if (di.Parent != null) {
            return Path.Combine(
                GetExactPathName(di.Parent.FullName), 
                di.Parent.GetFileSystemInfos(di.Name)[0].Name);
        } else {
            return di.Name.ToUpper();
        }
    }

下面是一些我的机器上工作的测试用例:

Here are some test cases that worked on my machine:

    static void Main(string[] args)
    {
        string file1 = @"c:\documents and settings\administrator\ntuser.dat";
        string file2 = @"c:\pagefile.sys";
        string file3 = @"c:\windows\system32\cmd.exe";
        string file4 = @"c:\program files\common files";
        string file5 = @"ddd";

        Console.WriteLine(GetExactPathName(file1));
        Console.WriteLine(GetExactPathName(file2));
        Console.WriteLine(GetExactPathName(file3));
        Console.WriteLine(GetExactPathName(file4));
        Console.WriteLine(GetExactPathName(file5));

        Console.ReadLine();
    }

如果该文件不存在,该方法将返回所提供的价值。

The method will return the supplied value if the file does not exists.

有可能会更快的方法(这使用递归),但我不知道是否有任何明显的方法来做到这一点。

There might be faster methods (this uses recursion) but I'm not sure if there are any obvious ways to do it.

这篇关于在Windows上获取实际的文件名(用适当的外壳)与.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆