Get media list for removable media in C #

Hi, I need to detect all removable media I have in the drop-down menu in C #

Any help would be appreciated

thanks

+7
source share
3 answers

You can use the DriveInfo type to get a list of drives. You need to check the DriveType (enum) property

var drives = DriveInfo.GetDrives(); foreach (var drive in drives) { if (drive.DriveType == DriveType.Removable) { Console.WriteLine(drive.Name); } } 

You can also use LINQ-to-Objects to query drives:

 var drives = from drive in DriveInfo.GetDrives() where drive.DriveType == DriveType.Removable select drive; foreach(var drive in drives) { Console.WriteLine(drive.Name); } 

Like @TheCodeKing mentioned, you can also use WMI to request disk information.

For example, you can request USB drives as follows:

 ManagementObjectCollection drives = new ManagementObjectSearcher( "SELECT Caption, DeviceID FROM Win32_DiskDrive WHERE InterfaceType='USB'" ).Get(); 

Add a reference to the System.Management assembly if you intend to use WMI.

If you want to populate the ComboBox in a Windows Forms application with this data, you need to bind the results to the ComboBox control.

For example:

 private void Form1_Load(object sender, EventArgs e) { var drives = from drive in DriveInfo.GetDrives() where drive.DriveType == DriveType.Removable select drive; comboBox1.DataSource = drives.ToList(); } 

Repeat:

  • Add a ComboBox control to a Windows form (drag it to the form from the toolbar)
  • Request removable drives.
  • Bind results to ComboBox.
+11
source

For this you use WMI, see this link for information and examples.

+1
source

All Articles