How to Detect a Usb Drive Has Been Plugged In

How to detect a USB drive has been plugged in?

It is easy to check for removable devices. However, there's no guarantee that it is a USB device:

var drives = DriveInfo.GetDrives()
.Where(drive => drive.IsReady && drive.DriveType == DriveType.Removable);

This will return a list of all removable devices that are currently accessible. More information:

  • The DriveInfo class (msdn documentation)
  • The DriveType enumeration (msdn documentation)

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

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

Start Method when USB was plugged in [C#]

You can use a ManagementEventWatcher for that.

There is an article on Microsoft called How to detect a removable disk that explains it nicely. I am using the code from the article almost as-is in production code, and it works on both Win7, Win8 and Win10.

Test Whether Employees Will Use Unknown USB Drive

You say the payload is an EXE file, so I will assume a Windows environment.

Windows AutoRun is still supported. Depending on its implementation, the user may be presented with an AutoPlay dialog, giving them choices. Unless they click on your executable, you may not receive email.

On most windows a USB insertion will generate System log Event 7036. With some additional logic and filtering, assuming the users are on a Windows domain, you could potentially see these events in their system logs.



Related Topics



Leave a reply



Submit