Detecting USB drive insertion and removal using windows service and c#

c# detect usb device connected
wm_devicechange c#
windows detect usb insertion
programmatically eject usb drive c#
c program to detect usb device
c# list usb devices
win32_devicechangeevent
c# listen to usb device

Looking into possibility of making an USB distributed application that will autostart on insertion of an USB stick and shutdown when removing the stick

Will use .Net and C#. Looking for suggestion how to approach this using C#?


Update: Two possible solutions implementing this as a service. - override WndProc or - using WMI query with ManagementEventWatcher

You can use WMI, it is easy and it works a lot better than WndProc solution with services.

Here is a simple example:

using System.Management;

ManagementEventWatcher watcher = new ManagementEventWatcher();
WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2");
watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
watcher.Query = query;
watcher.Start();
watcher.WaitForNextEvent();

To raise an event where ANY USB device is inserted, use the following: var watcher = new ManagementEventWatcher(); var query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2"); watcher. EventArrived += new EventArrivedEventHandler(watcher_EventArrived); watcher. Query = query; watcher. Detects drive plugged in and plugged out event perfectly. WMI Solution Vb.Net - www.vb-tips.com Works perfectly when a drive plugged in but cannot detect if a drive is plugged out. WMI Solution C# - stackoverflow.com Seems to work but failed to convert it to Vb.Net. C# code that I guess might work:

This works well for me, plus you can find out more information about the device.

using System.Management;

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);
    }
}

private 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);
}

An article on detecting insertion and removal of removable drives in C#. In Windows Forms applications, you can override the WndProc  You can also use WMI to detect insertion events. It’s a little bit more complicated than monitoring for WM_CHANGEDEVICE messages, but it does not require a window handle which may be useful if you are running in the background as a service.

Adding to VitalyB's post.

To raise an event where ANY USB device is inserted, use the following:

var watcher = new ManagementEventWatcher();
var query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2");
watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
watcher.Query = query;
watcher.Start();

This will raise an event whenever a USB device is plugged. It even works with a National Instruments DAQ that I'm trying to auto-detect.

Detecting USB drive insertion and removal using windows service and c# stick and shutdown when removing the stick. Will use .Net and C#. Questions: Looking into possibility of making an USB distributed application that will autostart on insertion of an USB stick and shutdown when removing the stick Will use .Net and C#. Looking for suggestion how to approach this using C#? Update: Two possible solutions implementing this as a service. – override WndProc or – using WMI

VitalyB's answer does't cover remove of the device. I changed it a bit to trigger the event both when media is inserted and removed and also code to get the drive letter of the inserted media.

using System;
using System.Management;

namespace MonitorDrives
{
    class Program
    {
        public enum EventType
        {
            Inserted = 2,
            Removed = 3
        }

        static void Main(string[] args)
        {
            ManagementEventWatcher watcher = new ManagementEventWatcher();
            WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2 or EventType = 3");

            watcher.EventArrived += (s, e) =>
            {
                string driveName = e.NewEvent.Properties["DriveName"].Value.ToString();
                EventType eventType = (EventType)(Convert.ToInt16(e.NewEvent.Properties["EventType"].Value));

                string eventName = Enum.GetName(typeof(EventType), eventType);

                Console.WriteLine("{0}: {1} {2}", DateTime.Now, driveName, eventName);
            };

            watcher.Query = query;
            watcher.Start();

            Console.ReadKey();
        }
    }
}

that will autostart on insertion of an USB stick and shutdown when removing the stick. Will use .Net and C#. Looking for suggestion how to approach this using C​  Here is some C# code to detect when a logical volume (e.g. USB Memory Stick) is inserted or removed via the WM_DEVICECHANGE message with WndProc. However this doesn’t tell you what has been inserted/removed, you will have to poll the drives manually to find out.

A little bit edit on all above answer:

using System.Management;

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();

        bgwDriveDetector.DoWork += bgwDriveDetector_DoWork;
        bgwDriveDetector.RunWorkerAsync();
    }

    private void DeviceInsertedEvent(object sender, EventArrivedEventArgs e)
    {
        string driveName = e.NewEvent.Properties["DriveName"].Value.ToString();
        MessageBox.Show(driveName + " inserted");
    }

    private void DeviceRemovedEvent(object sender, EventArrivedEventArgs e)
    {
        string driveName = e.NewEvent.Properties["DriveName"].Value.ToString();
        MessageBox.Show(driveName + " removed");
    }

    void bgwDriveDetector_DoWork(object sender, DoWorkEventArgs e)
    {
        var insertQuery = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2");
        var insertWatcher = new ManagementEventWatcher(insertQuery);
        insertWatcher.EventArrived += DeviceInsertedEvent;
        insertWatcher.Start();

        var removeQuery = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3");
        var removeWatcher = new ManagementEventWatcher(removeQuery);
        removeWatcher.EventArrived += DeviceRemovedEvent;
        removeWatcher.Start();
    }
}

Use the code provided to determine when a USB Thumb drive or Desktop-as-a​-Service Designed for Any Cloud ? If you run your application now, and add/​remove a thumb drive or contents into a C# class that mirrors the native Windows structure, Figure 4: Explorer view showing inserted drive. 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. Why Join Become a member Login No unread comment.

My NI USB device will occasionally lose connection to the computer, and I have and how can I get Windows to re-detect the device, without having to Using DevCon, you can enable, disable, restart, update, remove, and A valid service agreement may be required, and support options vary by country. This article describes my C# class called DriveDetector which will allow your program to receive a notification when a removable drive (such as a flash drive) is inserted or removed. It also supports notifications about pending removal of such a device and cancelling this removal.

How can my C# WPF Windows application detect when a USB device to receive device arrival and surprise removal event notification, a user  1..net - Detecting USB drive insertion and removal using windows service and c#; 2.windows - How to detect using c# if a pendrive is plugged into a USB port? 3.windows - Communicating with an USB device over “USB Virtual Serial Port” using C#? 4.c# - Can the physical USB port be identified programatically for a device in Windows?

Detecting USB drive insertion and removal using windows service and c#. My complete answer can be found here as a gist I found the answer to determining  How to Detect the Connection and Removal of USB Devices on a System Application Note AN_152 Version 1.1 Clearance No.: FTDI# 168 2 How to Detect a USB Device Insertion and Removal Windows Operating System broadcasts basic notifications message to any application with a top-level window by processing a WM_DEVICECHANGE.

Comments
  • Good question on the service trapping this event. My first thought is you have to mark your service as "allow to interact with desktop" and then create a hidden window. Safer option is probably to create a windows app that runs at startup - it can create the window and then communicate to the svc
  • Related: stackoverflow.com/questions/6003822/…
  • That works fine but How can I get drive letter of inserted USB?
  • This article seems to be getting this information in Powershell. Shouldn't be too hard to translate that to C#.
  • In your event handler, e.NewEvent.Properties["DriveName"].Value.ToString()
  • the query is clearly for volume changes, which has nothing to do usb added/removed. It doesn't even work for volume changes, at least on my system
  • using the above query is eating cpu resources, any idea why wmi causes this issue?
  • Works perfectly. Doesn't fire multiple events like some of the other answers here on insertion/removal. This should be the accepted answer.
  • I agree with @samuelAndThe, this seems the best aproach. If you are looking for also detect changes to hard drives and not only usb drives you can use the 'Win32_DiskDrive' class
  • private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e), why do you have (object sender, DoWorkEventArgs e)???(I committed an edit suggestion for this.)
  • Will this run on mono? Just asking, because started recently with that, and wmi is ms pure.
  • Everything is awesome but please remove that Thread.Sleep ^_^
  • @Lee Taylor That works fine but How can I get drive letter of inserted USB?
  • @NeverQuit - I only edited the question, ask @Syn! Also, if you have a new question then feel free to create one.