Skip to content

Instantly share code, notes, and snippets.

@jymcheong
Last active January 9, 2018 07:59
Show Gist options
  • Save jymcheong/a93b3a6171f1d4dbb1ebc737e6bc7dc4 to your computer and use it in GitHub Desktop.
Save jymcheong/a93b3a6171f1d4dbb1ebc737e6bc7dc4 to your computer and use it in GitHub Desktop.
Console test harness to get logical drive mount events
using System;
using System.Management;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Diagnostics;
namespace ConsoleDetectDriveMount
{
class DriveDetails
{
public string Name
{
get;
set;
}
public object Value
{
get;
set;
}
public DriveDetails(string name, object value)
{
Name = name;
Value = value;
}
}
class Program
{
private static ManagementEventWatcher _eventWatcher;
//https://stackoverflow.com/questions/8297842/detect-network-drive-mount-wmi
static void Main(string[] args)
{
_eventWatcher = new ManagementEventWatcher("SELECT * FROM __instanceCreationEvent WITHIN 5 WHERE TargetInstance ISA 'Win32_LogicalDisk'");
_eventWatcher.EventArrived += new EventArrivedEventHandler(EventArrived);
_eventWatcher.Start();
Console.ReadKey();
_eventWatcher.Stop();
}
static void EventArrived(object o, EventArrivedEventArgs eventargs)
{
ManagementBaseObject mo = (ManagementBaseObject)eventargs.NewEvent["TargetInstance"];
List<DriveDetails> listofdetails = new List<DriveDetails>();
foreach (PropertyData pd in mo.Properties)
listofdetails.Add(new DriveDetails(pd.Name, pd.Value));
Debug.WriteLine(JsonConvert.SerializeObject(listofdetails, Formatting.Indented));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment