如何在给定时间发现任何可用的 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
这是用于检查连接到计算机的任何可移动驱动器或 CDRom 驱动器的 VB.NET 代码:
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
将此代码修改为 ac# 等效代码并不难,而且还有更多driveType可用。
来自 MSDN:
在 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 的完整模块:
Imports System.IO
Module GetDriveNamesByType
Function GetDriveNames(Optional ByVal DType As DriveType = DriveType.Removable) As ListBox
For Each DN As System.IO.DriveInfo In My.Computer.FileSystem.Drives
If DN .DriveType = DType Then
GetDriveNames.Items.Add(DN.Name)
End If
Next
End Function
End Module
'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>