我们使用Visual Studio 2005来创建该示例程序,首先创建C# Windows应用程序空白项目,为解决方案和项目取名为 GetLogicDrives,在默认的Form1窗体上我们各放置一个ListView和一个Button控件,保留控件的默认名称不变,将 ListView1的View属性设为Details,双击ListView1的Columns属性,为详细信息视图添加5个列,分别为:盘符、卷标、类型、容量和可用空间,设置Button1的Text属性为Refresh,为该Button1添加单击事件,
C# Windows应用程序代码如下:
- private void button1_Click(object sender, EventArgs e)
- {
- listView1.Items.Clear();
- SelectQuery selectQuery = new SelectQuery("select * from win32_logicaldisk");
- ManagementObjectSearcher searcher = new ManagementObjectSearcher(selectQuery);
- int i=0;
- foreach (ManagementObject disk in searcher.Get()) {
- //盘符
- listView1.Items.Add(disk["Name"].ToString());
- //卷标
- try
- {
- listView1.Items[i].SubItems.Add(disk["VolumeName"].ToString());
- }
- catch
- {
- listView1.Items[i].SubItems.Add("设备未准备好");
- }
- //驱动器类型
- string DriveType;
- try
- {
- DriveType = disk["DriveType"].ToString();
- switch (DriveType)
- {
- case "0":
- listView1.Items[i].SubItems.Add("未知设备");
- break;
- case "1":
- listView1.Items[i].SubItems.Add("未分区");
- break;
- case "2":
- listView1.Items[i].SubItems.Add("可移动磁盘");
- break;
- case "3":
- listView1.Items[i].SubItems.Add("硬盘");
- break;
- case "4":
- listView1.Items[i].SubItems.Add("网络驱动器");
- break;
- case "5":
- listView1.Items[i].SubItems.Add("光驱");
- break;
- case "6":
- listView1.Items[i].SubItems.Add("内存磁盘");
- break;
- }
- }
- catch
- {
- listView1.Items[i].SubItems.Add("未知类型");
- }
- //容量
- try
- {
- listView1.Items[i].SubItems.Add(GetSizeUseUnit(disk["Size"].ToString()));
- }
- catch
- {
- listView1.Items[i].SubItems.Add("设备未准备好");
- }
- //剩余空间
- try
- {
- listView1.Items[i].SubItems.Add(GetSizeUseUnit(disk["FreeSpace"].ToString()));
- }
- catch
- {
- listView1.Items[i].SubItems.Add("设备未准备好");
- }
- i++;
- }
- }
以上是C# Windows应用程序的介绍
【编辑推荐】