如何在给定时间发现任何可用的USB存储设备和/或CD / DVD刻录机(使用C#.Net2.0)。
我想向用户提供可以存储文件以便物理移除的设备选择 - 即不是硬盘驱动器。
答案 0 :(得分:9)
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
答案 1 :(得分:1)
这是用于检查连接到计算机的任何可移动驱动器或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
将此代码修改为c#等效代码并不难,并且有更多 driveType 可用。
From MSDN:
答案 2 :(得分:1)
在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);
}
}
答案 3 :(得分:0)
这是VB.NET的完整模块:
进口System.IO
模块GetDriveNamesByType
函数GetDriveNames(可选ByVal DType As DriveType = DriveType.Removable)作为ListBox
对于每个DN As System.IO.DriveInfo在My.Computer.FileSystem.Drives中
如果DN.DriveType = DType那么
GetDriveNames.Items.Add(DN.Name)
结束如果
下一个
结束功能
结束模块
'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>