Working with USB devices in .NET
Using .Net (C#), how can you work with USB devices?
How can you detect USB events (connections/disconnections) and how do you communicate with devices (read/write).
Is there a native .Net solution to do this?
I've tried using SharpUSBLib and it screwed up my computer (needed a system restore). Happened to a coworker on the same project too.
I've found an alternative in LibUSBDotNet: http://sourceforge.net/projects/libusbdotnet Havn't used it much yet but seems good and recently updated (unlike Sharp).
EDIT: As of mid-February 2017, LibUSBDotNet was updated about 2 weeks ago. Meanwhile SharpUSBLib has not been updated since 2004.
There is no native (e.g., System libraries) solution for this. That's the reason why SharpUSBLib exists as mentioned by moobaa.
If you wish to roll your own handler for USB devices, you can check out the SerialPort class of System.IO.Ports.
I used the following code to detect when USB devices were plugged and unplugged from my computer:
class USBControl : IDisposable
{
// used for monitoring plugging and unplugging of USB devices.
private ManagementEventWatcher watcherAttach;
private ManagementEventWatcher watcherRemove;
public USBControl()
{
// Add USB plugged event watching
watcherAttach = new ManagementEventWatcher();
//var queryAttach = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2");
watcherAttach.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
watcherAttach.Query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2");
watcherAttach.Start();
// Add USB unplugged event watching
watcherRemove = new ManagementEventWatcher();
//var queryRemove = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3");
watcherRemove.EventArrived += new EventArrivedEventHandler(watcher_EventRemoved);
watcherRemove.Query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3");
watcherRemove.Start();
}
/// <summary>
/// Used to dispose of the USB device watchers when the USBControl class is disposed of.
/// </summary>
public void Dispose()
{
watcherAttach.Stop();
watcherRemove.Stop();
//Thread.Sleep(1000);
watcherAttach.Dispose();
watcherRemove.Dispose();
//Thread.Sleep(1000);
}
void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
Debug.WriteLine("watcher_EventArrived");
}
void watcher_EventRemoved(object sender, EventArrivedEventArgs e)
{
Debug.WriteLine("watcher_EventRemoved");
}
~USBControl()
{
this.Dispose();
}
}
You have to make sure you call the Dispose() method when closing your application. Otherwise, you will receive a COM object error at runtime when closing.