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

我想向用户提供一种可以存储文件以进行物理删除的设备选择 - 即不是硬盘。

有帮助吗?

解决方案

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/en-us/library/system.io.driveinfo.aspx

其他提示

这是 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

将此代码修改为 C# 等效代码并不难,甚至更多 驱动器类型的可用。
来自 MSDN:

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

在 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);
    }

}

这是 VB.NET 的完整模块:
导入系统.IO
模块 GetDriveNamesByType
函数 GetDriveNames(可选 ByVal DType As DriveType = DriveType.Removable) As ListBox
对于 My.Computer.FileSystem.Drives 中的每个 DN 作为 System.IO.DriveInfo
如果 DN.DriveType = DType 那么
GetDriveNames.Items.Add(DN.名称)
万一
下一个
结束功能
终端模块

'Drive Types <br>
'Unknown: The type of drive is unknown. <br>
'NoRootDirectory: The drive does not have a root directory. <br>
'Removable: The drive is a removable storage device, such as a floppy disk drive or a USB flash drive. <br>
'Fixed: The drive is a fixed disk. <br>
'Network: The drive is a network drive. <br>
'CDRom: The drive is an optical disc device, such as a CD or DVD-ROM. <br>
'Ram: The drive is a RAM disk. <br>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top