Get the drive letter from a path string or FileInfo

Well, there's also this:

FileInfo file = new FileInfo(path);
DriveInfo drive = new DriveInfo(file.Directory.Root.FullName);

And hey, why not an extension method?

public static DriveInfo GetDriveInfo(this FileInfo file)
{
    return new DriveInfo(file.Directory.Root.FullName);
}

Then you could just do:

DriveInfo drive = new FileInfo(path).GetDriveInfo();

FileInfo f = new FileInfo(path);    
string drive = Path.GetPathRoot(f.FullName);

This will return "C:\". That's really the only other way.

Tags:

C#

File Io