If you want to disable writing to USB altogether there is an excellent article here:
Developing a USB Storage Device Protection Tool with C#[
^]
Another approach is to detect the USB drive being mounted and then keep track of it, there is a complexity though, that external harddrives does not register like the usb flash drives, but essentially keeping track of attached devices can be done like this
using System;
using System.IO;
using System.Linq;
using System.Management;
using System.Threading;
namespace UsbDetector
{
class Program
{
private static bool clear;
static void Main(string[] args)
{
Console.WriteLine("Monitoring for DeviceAttaced event");
clear = false;
using (var 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();
while (!clear)
{
Console.WriteLine("Waiting for method clear signal");
Thread.Sleep(1000);
}
}
Console.WriteLine("Exitting");
}
public static void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
Console.WriteLine("Drive mounted " + e.NewEvent.Properties["DriveName"].Value);
var driveInfo = DriveInfo.GetDrives().FirstOrDefault(d => d.Name == e.NewEvent.Properties["DriveName"].Value.ToString() + "\\");
if(driveInfo.DriveType == DriveType.Fixed)
{
Console.WriteLine("Drive is a Fixed type, could be an external harddisk connected via USB");
}
if(driveInfo.DriveType == DriveType.Removable)
{
Console.WriteLine("Drive type is Removeable, could be a USB flash drive");
}
clear = true;
}
}
}