Drive letter from URI type file path in C#

﹥>﹥吖頭↗ 提交于 2019-12-21 08:18:08

问题


What is the easiest way to get the drive letter from a URI type file path such as

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

I know I can do (path here is a string containing the text above)

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

but it feels a bit clumsy. Is there a way to do it without using String.Replace or similar?


回答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:\\
}



回答2:


This can be done using the following code:

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


来源:https://stackoverflow.com/questions/12685797/drive-letter-from-uri-type-file-path-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!