属性方法
在进行程序开发时,需要获取驱动器的相关信息。在C#中可以调用DriveInfo类。
DriveInfo类提供对驱动器的信息访问。其属性方法如下
属性 | 说明 |
---|---|
AvailableFreeSpace | 指示驱动器上的可用空闲空间总量(以字节为单位)。 |
DriveFormat | 获取文件系统的名称,例如 NTFS 或 FAT32。 |
DriveType | 获取驱动器类型,如 CD-ROM、可移动、网络或固定。 |
IsReady | 获取一个指示驱动器是否已准备好的值。 |
Name | 获取驱动器的名称,如 C:\。 |
RootDirectory | 获取驱动器的根目录。 |
TotalFreeSpace | 获取驱动器上的可用空闲空间总量(以字节为单位)。 |
TotalSize | 获取驱动器上存储空间的总大小(以字节为单位)。 |
VolumeLabel | 获取或设置驱动器的卷标。 |
常用方法:GetDrives()。静态方法,检索计算机上所有逻辑驱动器的驱动器名称
Demo案例
需求效果
获取电脑所有驱动器以及对应的相关信息
程序代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 驱动器访问
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label7_Click(object sender, EventArgs e)
{
}
private void comboBox1_Click(object sender, EventArgs e)
{
comboBox1.Items.Clear();
DriveInfo[] allDriver = DriveInfo.GetDrives();
foreach (DriveInfo d in allDriver)
if(d.IsReady)
{
comboBox1.Items.Add(d.Name);
}
}
private void button1_Click(object sender, EventArgs e)
{
string StrTemp = comboBox1.SelectedItem.ToString();
long DriveSize = 1073741824;
DriveInfo driveInfo = new DriveInfo(StrTemp.Substring(0, 1));
textBox1.Text = driveInfo.DriveType.ToString();//驱动器类型
textBox2.Text = driveInfo.RootDirectory.ToString();//驱动器根目录
textBox3.Text = (driveInfo.TotalFreeSpace/ DriveSize).ToString();//可用空闲空间,单位为M
textBox4.Text = (driveInfo.TotalSize / DriveSize).ToString();//存储空间总大小
textBox5.Text = driveInfo.DriveFormat.ToString();//文件系统名称
}
}
}