Sending Mail To Admin On USB Insertion or Removal In C#

By 1st July 2019C#

Here is the c# console code to create a event watcher to monitor, if any usb attached or detached from PC.

Simple just create a console application in visual studio and install a package from nuget to import namespace System.Management.

Install-Package System.Management -Version 4.5.0

And Code is Bellow :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;

namespace USB
    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);
                Console.WriteLine("Mail admin"); //You can write your email code here

            watcher.Query = query;


you can write your email sending code after Console.WriteLine(“{0}: {1} {2}”, DateTime.Now, driveName, eventName);