在c#中获取可移动媒体驱动器列表

Sha*_*ara 8 c# detect removable

嗨我需要在c#中检测所有可移动媒体驱动器ia下拉菜单

任何帮助将不胜感激

谢谢

Chr*_*ers 12

您可以使用DriveInfo类型来检索驱动器列表.您需要检查DriveType属性(枚举)

var drives = DriveInfo.GetDrives();
foreach (var drive in drives)
{
    if (drive.DriveType == DriveType.Removable)
    {
        Console.WriteLine(drive.Name);
    }
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用LINQ-to-Objects查询驱动器:

var drives = from drive in DriveInfo.GetDrives()
             where drive.DriveType == DriveType.Removable
             select drive;

foreach(var drive in drives)
{
    Console.WriteLine(drive.Name);
}
Run Code Online (Sandbox Code Playgroud)

与提到的@TheCodeKing一样,您也可以使用WMI查询驱动器信息.

例如,您可以通过以下方式查询USB记忆棒:

ManagementObjectCollection drives = new ManagementObjectSearcher(
    "SELECT Caption, DeviceID FROM Win32_DiskDrive WHERE InterfaceType='USB'"
).Get();
Run Code Online (Sandbox Code Playgroud)

如果要使用WMI,请添加对System.Management程序集的引用.

如果要使用此数据填充Windows窗体应用程序中的ComboBox,则需要将结果绑定到ComboBox控件.

例如:

private void Form1_Load(object sender, EventArgs e)
{
    var drives = from drive in DriveInfo.GetDrives()
                 where drive.DriveType == DriveType.Removable
                 select drive;

    comboBox1.DataSource = drives.ToList();
}
Run Code Online (Sandbox Code Playgroud)

概括:

  1. 将一个ComboBox控件添加到Windows窗体(将其拖放到工具箱中的窗体上)
  2. 查询可移动驱动器.
  3. 将结果绑定到ComboBox.

  • 另请注意,如果要包含CD-Rom驱动器,则在"DriveType"枚举中不会将它们视为"可移动".您可能还想检查`|| drive.DriveType == DriveType.CDRom` (2认同)