4

I wrote a c# program to find newly inserted USB drive and its drive letter. Now when I run this program I got the insertion event and couldn't get the drive letter. Can anyone suggest me an idea to do this?

code

static void Main(string[] args)
{
    ManagementEventWatcher mwe_creation; //Object creation for 'ManagementEventWatcher' class is used to listen the temporary system event notofications based on specific query. 
    WqlEventQuery q_creation = new WqlEventQuery(); //Represents WMI(Windows Management Instrumentation) event query in WQL format for more information goto www.en.wikipedia.org/wiki/WQL
    q_creation.EventClassName = "__InstanceCreationEvent";// Sets the eventclass to the query
    q_creation.WithinInterval = new TimeSpan(0, 0, 2);    // Setting up the time interval for the event check(here, it is 2 Seconds)
    q_creation.Condition = @"TargetInstance ISA 'Win32_DiskDriveToDiskPartition'"; //Sets which kind of event  to be notified
    mwe_creation = new ManagementEventWatcher(q_creation); //Initializing new instance
    mwe_creation.EventArrived += new EventArrivedEventHandler(USBEventArrived_Creation);//Calling up 'USBEventArrived_Creation' method when the usb storage plug-in event occured
    mwe_creation.Start(); // Starting to listen to the system events based on the given query
    while (true) ;

}
static void USBEventArrived_Creation(object sender, EventArrivedEventArgs e){

    Console.WriteLine("USB PLUGGED IN!");
    ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
    foreach (var property in instance.Properties)
    {

        if (property.Name == "Name")
            Console.WriteLine(property.Name + " = " + property.Value);
    }

}
Hybrid Developer
  • 2,320
  • 1
  • 34
  • 55
  • have you tried this var drives = DriveInfo.GetDrives() .Where(drive => drive.IsReady && drive.DriveType == DriveType.Removable); – rashfmnb Apr 25 '16 at 06:40
  • This will pick all the removable drives present in the system – Hybrid Developer Apr 25 '16 at 06:46
  • have a look in to this satckoverflow link it has too much info http://stackoverflow.com/questions/6003822/how-to-detect-a-usb-drive-has-been-plugged-in – rashfmnb Apr 25 '16 at 06:49
  • I found a solution from http://www.codeproject.com/Messages/2126647/Re-Csharp-USB-Detection.aspx they are using `TargetInstance ISA 'Win32_LogicalDisk'` instead `TargetInstance ISA 'Win32_DiskDriveToDiskPartition'` and its working for me. – Hybrid Developer Apr 25 '16 at 07:30
  • Still i don't know why it is working cause all my USB Flash Drives are Primary Partitions. Can anyone explain this ? – Hybrid Developer Apr 25 '16 at 07:34
  • Win32_DiskDriveToDiskPartition does not have any events so this can't work. Google "Win32_VolumeChangeEvent" to get ahead. [This blog post](https://alitarhini.wordpress.com/2010/11/05/listen-for-removable-device-events/) looks good. – Hans Passant Apr 25 '16 at 07:46

1 Answers1

0

You may be working too hard to recreate a pre-existing soultion. Here is a Public-Licensed project made by Stephen Mcohn that provides exactly the interface you need and appears to be well documented:

http://www.codeproject.com/Articles/63878/Enumerate-and-Auto-Detect-USB-Drives

Here is how he filtered for just USB drives

new ManagementObjectSearcher(
        "select DeviceID, Model from Win32_DiskDrive " +
         "where InterfaceType='USB'").Get())

Here is how the specific drive letter was recovered

Getting the specific drive letter was accomplished using Associators to get the Win32_LogicalDisk which can then give the device ID (e.g. drive letter).

Microsoft Provided a VB code example that you can port if you don't want to just import Stephen's whole module:

ComputerName = "."
Set wmiServices  = GetObject ( _
    "winmgmts:{impersonationLevel=Impersonate}!//" & ComputerName)
' Get physical disk drive
Set wmiDiskDrives =  wmiServices.ExecQuery ( "SELECT Caption, DeviceID FROM Win32_DiskDrive")

For Each wmiDiskDrive In wmiDiskDrives
    WScript.Echo "Disk drive Caption: " & wmiDiskDrive.Caption & VbNewLine & "DeviceID: " & " (" & wmiDiskDrive.DeviceID & ")"

    'Use the disk drive device id to
    ' find associated partition
    query = "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" _
        & wmiDiskDrive.DeviceID & "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition"    
    Set wmiDiskPartitions = wmiServices.ExecQuery(query)

    For Each wmiDiskPartition In wmiDiskPartitions
        'Use partition device id to find logical disk
        Set wmiLogicalDisks = wmiServices.ExecQuery _
            ("ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" _
             & wmiDiskPartition.DeviceID & "'} WHERE AssocClass = Win32_LogicalDiskToPartition") 

        For Each wmiLogicalDisk In wmiLogicalDisks
            WScript.Echo "Drive letter associated" _
                & " with disk drive = " _ 
                & wmiDiskDrive.Caption _
                & wmiDiskDrive.DeviceID _
                & VbNewLine & " Partition = " _
                & wmiDiskPartition.DeviceID _
                & VbNewLine & " is " _
                & wmiLogicalDisk.DeviceID
        Next      
    Next
Next
James Fegan
  • 129
  • 1
  • 7