C#中各類獲取設備存儲信息的各類方法

普通WINFORM程序:

1.使用System.IO.DriveInfo來遍歷磁盤及其分區信息

引用System.IO後即可調用DriveInfo類來對磁盤空間信息進行遍歷了,此外DriveInfo只有在普通WINFORM中可以調用,WINCE項目中未封裝此類。

//獲取磁盤設備
DriveInfo[] drives = DriveInfo.GetDrives();
//遍歷磁盤
foreach (DriveInfo drive in drives)
{
string drvInfo = "磁盤分區號:" + drive.Name + "盤" + "\t\n" +
"磁盤格式:" + drive.DriveFormat + "\t\n" +
"磁盤品牌:" + drive.DriveType + "\t\n" +
"磁盤卷標:" + drive.VolumeLabel + "\t\n" +
"磁盤總容量" + drive.TotalSize + "\t\n" +
"磁盤空餘容量:" + drive.TotalFreeSpace;
}

2.使用System.Management.ManagementClass來遍歷磁盤設備的各類屬性
與DriveInfo一樣,WINCE項目中未封裝此類。

ArrayList propNames = new ArrayList();
ManagementClass driveClass = new ManagementClass("Win32_DiskDrive");
PropertyDataCollection props = driveClass.Properties;
//獲取本地磁盤各類屬性值
foreach (PropertyData driveProperty in props)
propNames.Add(driveProperty.Name);
int idx = 0;
ManagementObjectCollection drives = driveClass.GetInstances();
//遍歷該磁盤的各類屬性
foreach (ManagementObject drv in drives)
{
MessageBox.Show(string.Format(" 磁盤({0})的所有屬性 ", idx + 1));
foreach (string strProp in propNames)
MessageBox.Show(string.Format("屬性: {0}, 值: {1} ", strProp, drv[strProp]));
}


3.調用API函數GetVolumeInformation來獲取磁盤信息
定義API函數時,函數傳參前的"ref"亦可不加,但不加"ref"傳參不會有返回值。

[DllImport("Kernel32.dll")]
public static extern bool GetVolumeInformation(
ref string lpRootPathName, // 系統盤符根目錄或網絡服務器資源名
ref string lpVolumeNameBuffer, // 磁盤卷標
ref int nVolumeNameSize, // 磁盤卷標字符串的長度
ref int lpVolumeSerialNumber, // 磁盤卷標的序列號
ref int lpMaximumComponentLength, // 文件名長度支持
ref int lpFileSystemFlags, // 文件系統標記
ref string lpFileSystemNameBuffer, // 文件系統類型
ref int nFileSystemNameSize); // 文件系統類型字符串長度

調用 string strDriver = Path.GetFullPath(@"\");
bool res;
int serialNum = 0;
int size = 0;
string volume = "";
string vl= "";
string type = "";
string tl= "";
res = GetVolumeInformation(ref strDriver,ref volume,ref vl, ref serialNum, ref size, 0,ref type,ref tl);
if (res)
{
MessageBox.Show("卷標: " + volume.Trim());
MessageBox.Show(string.Format("卷序列號: {0:X}", serialNum));
MessageBox.Show("文件名最大長度: " + size);
MessageBox.Show("磁盤分區系統: " + type);
}
else
{
MessageBox.Show("該磁盤不存在");
}
WINCE程序:

1.調用API函數GetDiskFreeSpaceExW來獲取磁盤信息

在WINCE中"CoreDll.dll"相對應普通XP中的"Kernel32.dll",其方法調用亦和GetVolumeInformation類似

//獲取磁盤信息
[DllImport("CoreDll.dll")]
public static extern long GetDiskFreeSpaceExW(
ref string lpRootPathName,//不包括卷名的一個磁盤根路徑
ref long lpSectorsPerCluster,//用於裝載一個簇內扇區數的變量
ref long lpBytesPerSector,//用於裝載一個扇區內字節數的變量
ref long lpNumberOfFreeClusters,//用於裝載磁盤上剩餘簇數的變量
ref long lpTtoalNumberOfClusters//用於裝載磁盤上總簇數的變量
);

文章源自:烈火網,原文:http://www.veryhuo.com/a/view/36317.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章