Detect Insertion and Removal of USB Drive C#

Posted: November 7, 2014 in Uncategorized

I have located the following code and have been trying to change this so that I know if the USB device has been inserted or removed.

using System;

using System.Collections.Generic;

using System.Text;

using System.Management;

 

namespace WMIUSBConsolApplication

{

class Program

{

static void Main(string[] args)

{

AddInsetUSBHandler();

AddRemoveUSBHandler();

for (; ; ) ;

}

static ManagementEventWatcher w = null;

public static void AddRemoveUSBHandler()

{

WqlEventQuery q;

ManagementScope scope = new ManagementScope(“root\\CIMV2”);

scope.Options.EnablePrivileges = true;

try

{

q = new WqlEventQuery();

q.EventClassName = “__InstanceDeletionEvent”;

q.WithinInterval = new TimeSpan(0, 0, 3);

q.Condition = @”TargetInstance ISA ‘Win32_USBHub'”;

w = new ManagementEventWatcher(scope, q);

w.EventArrived += new EventArrivedEventHandler(USBRemoved);

w.Start();

}

 

catch (Exception e)

{

 

Console.WriteLine(e.Message);

if (w != null)

w.Stop();

}

}

 

static void AddInsetUSBHandler()

{

WqlEventQuery q;

ManagementScope scope = new ManagementScope(“root\\CIMV2”);

scope.Options.EnablePrivileges = true;

 

try

{

q = new WqlEventQuery();

q.EventClassName = “__InstanceCreationEvent”;

q.WithinInterval = new TimeSpan(0, 0, 3);

q.Condition = @”TargetInstance ISA ‘Win32_USBHub'”;

w = new ManagementEventWatcher(scope, q);

w.EventArrived += new EventArrivedEventHandler(USBAdded);

w.Start();

}

catch (Exception e)

{

 

Console.WriteLine(e.Message);

if (w != null)

w.Stop();

}

}

 

public static void USBAdded(object sender, EventArgs e)

{

Console.WriteLine(“A USB device inserted”);

}

 

public static void USBRemoved(object sender, EventArgs e)

{

Console.WriteLine(“A USB device removed”);

}

}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s