【问题标题】:Drive letter from URI type file path in C#C#中URI类型文件路径的驱动器号
【发布时间】:2012-09-23 00:59:33
【问题描述】:

从 URI 类型文件路径获取驱动器号的最简单方法是什么,例如

file:///D:/Directory/File.txt

我知道我能做到(这里的路径是一个包含上述文本的字符串)

path = path.Replace(@"file:///", String.Empty);
path = System.IO.Path.GetPathRoot(path);

但感觉有点笨拙。有没有办法在不使用 String.Replace 或类似的情况下做到这一点?

【问题讨论】:

    标签: c# filepath


    【解决方案1】:
    var uri = new Uri("file:///D:/Directory/File.txt");
    if (uri.IsFile)
    {
        DriveInfo di = new DriveInfo(uri.LocalPath);
        var driveName = di.Name; // Result: D:\\
    }
    

    【讨论】:

    • 加个支票会更好if(uri.IsFile)
    • 谢谢。这正是我想要的。
    【解决方案2】:

    这可以使用以下代码完成:

        string path = "file:///D:/Directory/File.txt";
        if(Uri.IsWellFormedUriString(path, UriKind.RelativeOrAbsolute)) {
            Uri uri = new Uri(path);
            string actualPath = uri.AbsolutePath;
        }
    

    【讨论】:

      猜你喜欢
      • 2016-09-16
      • 1970-01-01
      • 1970-01-01
      • 2011-10-01
      • 1970-01-01
      • 2016-02-15
      • 2019-05-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多