如何发现USB存储设备和可写CD / DVD驱动器(C#)

时间:2020-03-05 18:49:59  来源:igfitidea点击:

如何发现给定时间可用的任何USB存储设备和/或者CD / DVD刻录机(使用C.Net2.0)。

我想为用户提供选择可以存储文件以进行物理删除的设备(即不是硬盘驱动器)。

解决方案

回答

这是VB.NET代码,用于检查连接到计算机的任何可移动驱动器或者CDRom驱动器:

Me.lstDrives.Items.Clear()
For Each item As DriveInfo In My.Computer.FileSystem.Drives
    If item.DriveType = DriveType.Removable Or item.DriveType = DriveType.CDRom Then
        Me.lstDrives.Items.Add(item.Name)
    End If
Next

将该代码修改为等效代码并不难,并且可以使用更多的driveType。
从MSDN:

  • 未知:驱动器类型未知。
  • NoRootDirectory:驱动器没有根目录。
  • 可移动设备:驱动器是可移动存储设备,例如软盘驱动器或者USB闪存驱动器。
  • 固定:驱动器是固定磁盘。
  • 网络:该驱动器是网络驱动器。
  • CDRom:驱动器是光盘设备,例如CD或者DVD-ROM。
  • Ram:该驱动器是RAM磁盘。

回答

using System.IO;

DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
  if (d.IsReady && d.DriveType == DriveType.Removable)
  {
    // This is the drive you want...
  }
}

DriveInfo类文档在这里:

http://msdn.microsoft.com/zh-CN/library/system.io.driveinfo.aspx

回答

在c中,我们可以通过使用System.IO.DriveInfo类获得相同的结果

using System.IO;

public static class GetDrives
{
    public static IEnumerable<DriveInfo> GetCDDVDAndRemovableDevices()
    {
        return DriveInfo.GetDrives().
            Where(d => d.DriveType == DriveType.Removable
            && d.DriveType == DriveType.CDRom);
    }

}