Ken Zhang
Ken Zhang

Reputation: 21

Portable device detection using C#

I have a problem detecting portable devices, specifically samsung phone or iphone. I need to develop a program that will start once the detection of a portable plug-in and stop, once plugged out.

I've been trying this code, but only works with usb devices with storage, and not on portable device.

private void DeviceInsertedEvent(object sender, EventArrivedEventArgs e)
{
    ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
    foreach (var property in instance.Properties)
    {
        Console.WriteLine(property.Name + " = " + property.Value);
    }
}

void DeviceRemovedEvent(object sender, EventArrivedEventArgs e)
{
    ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
    foreach (var property in instance.Properties)
    {
        Console.WriteLine(property.Name + " = " + property.Value);
    }
}            

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    WqlEventQuery insertQuery = new WqlEventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'");

    ManagementEventWatcher insertWatcher = new ManagementEventWatcher(insertQuery);
    insertWatcher.EventArrived += new EventArrivedEventHandler(DeviceInsertedEvent);
    insertWatcher.Start();

    WqlEventQuery removeQuery = new WqlEventQuery("SELECT * FROM __InstanceDeletionEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'");
    ManagementEventWatcher removeWatcher = new ManagementEventWatcher(removeQuery);
    removeWatcher.EventArrived += new EventArrivedEventHandler(DeviceRemovedEvent);
    removeWatcher.Start();

    // Do something while waiting for events
    System.Threading.Thread.Sleep(20000000);
}

please help. thanks

Upvotes: 0

Views: 1649

Answers (1)

jiten
jiten

Reputation: 5264

Have you tried this:

System.IO.DriveInfo [] drives = System.IO.DriveInfo.GetDrives ();
foreach (System.IO.DriveInfo drive in drives)
{
  if (drive.DriveType == DriveType.Removable)
  {
    Console.WriteLine ("Found removable drive {0}", drive.Name);
  }
}

For More about DriveInfo

Upvotes: 1

Related Questions