1

I wanna write program that detects flash drives.
But there's a problem.
Code:

DriveInfo[] allDrives = DriveInfo.GetDrives();

foreach (DriveInfo drive in DriveInfo.GetDrives())
{
    if (drive.DriveType == DriveType.Removable)
    {
    }
}

It works well, but it detects cdrom too. How to prevent it?

Chris
  • 26,361
  • 5
  • 21
  • 42
Mudzay
  • 71
  • 8
  • 1
    That suggests that your computer is reporting the wrong type for the cdrom drive. Do you have some disc writing software which could cause that? – Andrew Morton Mar 28 '16 at 12:11
  • I don't use any burning software because i don't really burn cd's and dvd's Btw. my pc is running windows 10 right now but i will install windows 7 soon – Mudzay Mar 28 '16 at 15:49
  • I previously checked with Windows 7, so just to make sure I have checked on Windows 10 too. It still looks like your computer is reporting the wrong type for the optical drive. Does it happen to be connected via USB? (I haven't got a USB DVD drive to check with.) – Andrew Morton Mar 28 '16 at 16:02

1 Answers1

3

I have no answer why your code is not working. But if you want to detect USB-devices, you could also try it with the WMI like this:

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

Add the System.Management assembly to your project to do it like this.

Fruchtzwerg
  • 10,999
  • 12
  • 40
  • 49
  • Thanks, gonna test just now. – Mudzay Mar 28 '16 at 15:51
  • I added System.Management assembly but this code don't work. I get "The type or namespace name 'ManagementObjectCollection' could not be found (are you missing a using directive or an assembly reference?)" error – Mudzay Mar 28 '16 at 15:56
  • Look here how to add the missing assembly: https://msdn.microsoft.com/de-de/library/ee231595%28v=vs.110%29.aspx here is also an example: http://stackoverflow.com/questions/2157133/how-do-i-add-an-assembly-to-a-visual-studio-project-and-reference-it you have to add the System.Management assembly to your project – Fruchtzwerg Mar 28 '16 at 16:04
  • Then the "ManagementObjectCollection" should be found? – Fruchtzwerg Mar 28 '16 at 16:07
  • Thats extraordinary ... :-) – Fruchtzwerg Mar 28 '16 at 16:43