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
How to Automatically Scroll to the Bottom of a Multiline Text Box
How to Get Intptr from Byte[] in C#
Editing Dictionary Values in a Foreach Loop
Foreach VS Somelist.Foreach(){}
How to Deploy Application with SQL Server Database on Clients
List<T> VS Bindinglist<T> Advantages/Disadvantages
C# Selenium 'Expectedconditions Is Obsolete'
How to Get More Than 1000 Records from a Directorysearcher
Implementing Zero or One to Zero or One Relationship in Ef Code First by Fluent API
How to Check a Input Ip Fall in a Specific Ip Range
Download Image from the Site in .Net/C#
C#:What If a Static Method Is Called from Multiple Threads
Entity Framework Very Slow to Load for First Time After Every Compilation
Why Interface Layer/Abstract Classes Required in Our Project