How to discover USB storage devices and writable CD/DVD drives (C#)
Question
How can I discover any USB storage devices and/or CD/DVD writers available at a given time (using C# .Net2.0).
I would like to present users with a choice of devices onto which a file can be stored for physically removal - i.e. not the hard drive.
Solution
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...
}
}
The DriveInfo class documentation is here:
http://msdn.microsoft.com/en-us/library/system.io.driveinfo.aspx
OTHER TIPS
this is VB.NET code to check for any removable drives or CDRom drives attached to the computer:
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
it won't be that hard to modify this code into a c# equivalent, and more driveType's are available.
From MSDN:
- Unknown: The type of drive is unknown.
- NoRootDirectory: The drive does not have a root directory.
- Removable: The drive is a removable storage device, such as a floppy disk drive or a USB flash drive.
- Fixed: The drive is a fixed disk.
- Network: The drive is a network drive.
- CDRom: The drive is an optical disc device, such as a CD or DVD-ROM.
- Ram: The drive is a RAM disk.
in c# you can get the same by using the System.IO.DriveInfo class
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);
}
}
This is a complete module for 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>