detect when a removable disk is inserted using C#

    	static ManagementEventWatcher w = null;
    	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_USBControllerdevice'";
    			w = new ManagementEventWatcher(scope, q);
    			w.EventArrived += USBRemoved;
    			w.Start();
    		}
    		catch (Exception e) {
    			Console.WriteLine(e.Message);
    			if (w != null)
    			{
    				w.Stop();
    			}
    		}
    	}

    	static void AddInsertUSBHandler()
    	{
    		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_USBControllerdevice'";
    			w = new ManagementEventWatcher(scope, q);
    			w.EventArrived += USBInserted;
    			w.Start();
    		}
    		catch (Exception e) {
    			Console.WriteLine(e.Message);
    			if (w != null)
    			{
    				w.Stop();
    			}
    		}
    	}

    	static void USBInserted(object sender, EventArgs e)
    	{
    		Console.WriteLine("A USB device inserted");
    	}

    	static void USBRemoved(object sender, EventArgs e)
    	{
    		Console.WriteLine("A USB device removed");
    	}

How to use

    	Main()
    	{
    		AddInsertUSBHandler();
    		AddRemoveUSBHandler();
    		while (true) {}
    	}

http://stackoverflow.com/a/271251

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.