在.Net中處理系統(tǒng)文件相關(guān)的幾個(gè)類分別是File、Directory、FileInfo、DirectoryInfo、DriveInfo、FileSystemWatcher。本文介紹下這幾個(gè)類的用法。 1.File類提供靜態(tài)方法用來(lái)創(chuàng)建、移動(dòng)、復(fù)制、刪除文件的操作,并可以打開(kāi)文件流 2.Directory類提供靜態(tài)方法用來(lái)創(chuàng)建、移動(dòng)、復(fù)制、刪除目錄的操作 3.FileInfo類用類實(shí)例實(shí)現(xiàn)創(chuàng)建、復(fù)制、移動(dòng)、刪除文件的操作 4.DirectoryInfo提供創(chuàng)建、移動(dòng)、復(fù)制、刪除目錄的操作,并可以枚舉子目錄 5.DriveInfo可以獲得windows操作系統(tǒng)中的磁盤信息 6.FileSystemWatcher用來(lái)監(jiān)視文件或目錄變化,并引發(fā)事件 7.Path類提供文件名目錄名操作的靜態(tài)方法 File、FileInfo、Directory、DirectoryInfo這幾個(gè)類的使用方法都非常簡(jiǎn)單就不做贅述了。 1.如何使用DriveInfo獲得windows系統(tǒng)磁盤信息 不允許在程序中自己構(gòu)造DriveInfo的實(shí)例,可以通過(guò)DriveInfo的靜態(tài)方法GetDrives()獲得windows系統(tǒng)中所有的磁盤,包括硬盤,cd以及u盤;注意在訪問(wèn)磁盤屬性時(shí)需要先判斷其IsReady屬性是否為true,IsReady為false時(shí)訪問(wèn)磁盤的一些屬性時(shí)會(huì)拋出異常。如下實(shí)例代碼: 代碼如下: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO;
namespace aboutio { class Program { static void Main(string[] args) { DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo drive in drives) { if(drive.IsReady) Console.WriteLine("類型:{0} 卷標(biāo):{1} 名稱:{2} 總空間:{3} 剩余空間:{4}",drive.DriveType, drive.VolumeLabel,drive.Name,drive.TotalSize,drive.TotalFreeSpace); else Console.WriteLine("類型:{0} is not ready",drive.DriveType); }