加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

在Windows上使用.NET获取实际的文件名(具有正确的外壳)

发布时间:2020-12-13 21:07:23 所属栏目:Windows 来源:网络整理
导读:我想和 this question完全一样: 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)? 但是我需要
我想和 this question完全一样:

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)。

我看到FileInfo类上的FullName没有做到这一点。

我似乎NTFS是不区分大小写的,不管你的输入是否正确,总是会输入正确的。

获取正确的路径名称的唯一方法似乎找到像John Sibly所建议的文件。

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

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();
        }
    }

这里有一些在我的机器上工作的测试用例:

static void Main(string[] args)
    {
        string file1 = @"c:documents and settingsadministratorntuser.dat";
        string file2 = @"c:pagefile.sys";
        string file3 = @"c:windowssystem32cmd.exe";
        string file4 = @"c:program filescommon 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();
    }

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读