Пример #1
0
        private void threadRun()
        {
            var usbWatcher = new ManagementEventWatcher();

            usbWatcher.Query = new EventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2 OR EventType = 3");

            usbWatcher.EventArrived += (s, ea) =>
            {
                var driveName = $"{ea.NewEvent.Properties["DriveName"].Value}";
                var type      = (USBEventType)(Enum.Parse(typeof(USBEventType), $"{ea.NewEvent.Properties["EventType"].Value}"));

                //get detailed data on the drive that was inserted
                var availableDrives = DriveInfo.GetDrives();
                var info            = DriveInfo.GetDrives().Where(x => driveNameSanitizer(x.Name).Equals(driveNameSanitizer(driveName))).FirstOrDefault();

                Int64?        freeSpace  = null;
                Int64?        totalSpace = null;
                DirectoryInfo root       = null;
                string        volume     = null;
                if (info != null)
                {
                    freeSpace  = info.AvailableFreeSpace.BytesToGigabytes();
                    totalSpace = info.TotalFreeSpace.BytesToGigabytes();
                    volume     = info.VolumeLabel;
                    root       = info.RootDirectory;
                }

                var usbDisk = new USBDisk {
                    Name = driveName, Volume = volume, EntryPoint = root, AvailableSpace = freeSpace, TotalSpace = totalSpace
                };

                switch (type)
                {
                case USBEventType.Inserted:
                    DeviceInserted?.Invoke(this, new USBEventArgs(type, usbDisk));
                    break;

                case USBEventType.Removed:
                    DeviceRemoved?.Invoke(this, new USBEventArgs(type, usbDisk));
                    break;

                default:
                    throw new NotImplementedException("That type was not implemented");
                }
            };

            var cdWatcher = new ManagementEventWatcher();

            cdWatcher.Query = new EventQuery("SELECT * FROM Win32_LogicalDisk WHERE DriveType = 5");

            cdWatcher.EventArrived += (s, ea) =>
            {
            };

            if (WatchUSB)
            {
                usbWatcher.Start();
            }
            if (WatchCD)
            {
                cdWatcher.Start();
            }

            while (shouldWatch)
            {
                Thread.Sleep(250);
            }

            usbWatcher.Stop();
            cdWatcher.Stop();
        }
Пример #2
0
 public USBEventArgs(USBEventType Type, USBDisk Disk)
 {
     this.EventType = Type;
     this.Disk      = Disk;
 }