您的位置:首页 > 编程语言 > C#

C#中各类获取设备存储信息的各类方法

2014-05-08 22:44 417 查看
普通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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: