Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drive letter from URI type file path in C#

Tags:

c#

filepath

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?

like image 584
Henry H Avatar asked Oct 02 '12 07:10

Henry H


2 Answers

var uri = new Uri("file:///D:/Directory/File.txt");
if (uri.IsFile)
{
    DriveInfo di = new DriveInfo(uri.LocalPath);
    var driveName = di.Name; // Result: D:\\
}
like image 104
Furqan Safdar Avatar answered Oct 24 '22 00:10

Furqan Safdar


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;
    }
like image 37
platon Avatar answered Oct 24 '22 00:10

platon