2008-12-16 36 views
14

盤符這似乎是一個愚蠢的問題,所以這裏有雲:獲取從路徑字符串或FileInfo的

除了解析FileInfo.FullPath的字符串的驅動器號,然後使用DriveInfo(「C」 )等,看看是否有足夠的空間來寫這個文件。有沒有辦法從FileInfo獲取驅動器盤符?

+0

警告:這不會在所有情況下工作!僅僅因爲驅動器根目錄上有足夠的空間並不意味着當前目錄中有足夠的空間。同樣,根目錄中可能沒有空格,但當前目錄中有空格。 Windows至少能夠找出當前目錄中的空間,正如多個程序正確報告當前目錄中的空閒空間即使它與根目錄中的空間不匹配一樣。我還沒有調查如何做到這一點。 (我想到的情況是將卷映射到子目錄中。) – 2010-06-18 02:30:30

回答

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

這將返回 「C:\」。這是唯一的其他方法。

1

沒有錯,一個小串解析:-)

FullPath.SubString(0,1); 
+8

這是對路徑做出不安全的假設。考慮它實際上是\\ machinename \ share \ path \ filename.txt形式的UNC路徑名的情況。 – 2009-09-18 13:39:29

21

好,也就是:

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

哎,爲什麼不擴展方法?

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

然後,你可以只是做:

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

您可以使用此代碼獲取系統中所有驅動器:

foreach (DriveInfo objDrive in DriveInfo.GetDrives()) 
    { 
     Response.Write("</br>Drive Type : " + objDrive.Name); 
     Response.Write("</br>Drive Type : " + objDrive.DriveType.ToString()); 
     Response.Write("</br>Available Free Space : " + objDrive.AvailableFreeSpace.ToString() + "(bytes)"); 
     Response.Write("</br>Drive Format : " + objDrive.DriveFormat); 
     Response.Write("</br>Total Free Space : " + objDrive.TotalFreeSpace.ToString() + "(bytes)"); 
     Response.Write("</br>Total Size : " + objDrive.TotalSize.ToString() + "(bytes)"); 
     Response.Write("</br>Volume Label : " + objDrive.VolumeLabel); 
     Response.Write("</br></br>"); 

    } 
+1

將此回答推回到包含版主從您的帖子中刪除的垃圾鏈接是不合適的。 – 2012-11-05 14:48:26

相關問題