从 URI 类型文件路径获取驱动器号的最简单方法是什么,例如
file:///D:/Directory/File.txt
我知道我能做到(这里的路径是一个包含上述文本的字符串)
path = path.Replace(@"file:///", String.Empty);
path = System.IO.Path.GetPathRoot(path);
但感觉有点笨拙。有没有办法在不使用 String.Replace 或类似的情况下做到这一点?
var uri = new Uri("file:///D:/Directory/File.txt");
if (uri.IsFile)
{
DriveInfo di = new DriveInfo(uri.LocalPath);
var driveName = di.Name; // Result: D:\\
}
这可以使用以下代码完成:
string path = "file:///D:/Directory/File.txt";
if(Uri.IsWellFormedUriString(path, UriKind.RelativeOrAbsolute)) {
Uri uri = new Uri(path);
string actualPath = uri.AbsolutePath;
}