tags:

views:

739

answers:

4

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?

+1  A: 

Nothing wrong with a little string parsing :-)

FullPath.SubString(0,1);
Joel Martinez
This is making unsafe assumptions about the path. Consider the case where it is actually a UNC pathname of the form \\machinename\share\path\filename.txt.
Steven Sudit
+11  A: 
FileInfo f = new FileInfo(path);    
string drive = Path.GetPathRoot(f.FullName);

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

BFree
+1  A: 

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();
Dan Tao
A: 

Warning: This will not work in all cases!

Just because there is enough space on the root of a drive doesn't mean there is enough space in the current directory. Likewise there might not be the space at the root but there is space in the current directory.

Windows at least is capable of figuring out the space in the current directory as evidenced by multiple programs correctly reporting the free space in the current directory even when it doesn't match the space at the root. I have not investigated how to accomplish this.

(The situation I'm thinking of is volumes mapped into subdirectories.)

Loren Pechtel