Question

Get the drive letter from a path string or FileInfo

This may seem like a stupid question, so here goes:

Other than parsing the string of FileInfo.FullPath for the drive letter to then use DriveInfo("c") etc to see if there is enough space to write this file. Is there a way to get the drive letter from FileInfo?

 45  50133  45
1 Jan 1970

Solution

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

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

2008-12-16

Solution

 30

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();
2010-06-18