C#中各类获取设备存储信息的各类方法
普通WINFORM程序:
1.使用System.IO.DriveInfo来遍历磁盘及其分区信息
引用System.IO后即可调用DriveInfo类来对磁盘空间信息进行遍历了,此外DriveInfo只有在普通WINFORM中可以调用,WINCE项目中未封装此类。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//获取磁盘设备
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;
}
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项目中未封装此类。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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]));
}
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"传参不会有返回值。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
调用
View Code
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
WINCE程序:
1.调用API函数GetDiskFreeSpaceExW来获取磁盘信息
在WINCE中"CoreDll.dll"相对应普通XP中的"Kernel32.dll",其方法调用亦和GetVolumeInformation类似
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)