public void StartScanning(DriveInsertedEvent insertedEvent, DriveRemovedEvent removedEvent, bool displayFixedDrives) { stopCommand = false; this.DisplayFixedDrives = displayFixedDrives; Task.Run(new Action(() => { while (true) { List<DriveInfo> drives = new List<DriveInfo>(); foreach (var v in FilterDrives(DriveInfo.GetDrives().ToList())) { try { var dae = v.RootDirectory.EnumerateFiles(); drives.Add(v); } catch (Exception ex) { } } foreach (var v in drives) { if (!insertedDrives.Select(x => x.Name).Contains(v.Name)) { insertedEvent(v.Name); insertedDrives.Add(v); } } if (stopCommand) break; Thread.Sleep(ScanningInterval); } })); Task.Run(new Action(() => { while (true) { List<DriveInfo> drives = new List<DriveInfo>(); foreach (var v in FilterDrives(DriveInfo.GetDrives().ToList())) { try { var dae = v.RootDirectory.EnumerateFiles(); drives.Add(v); } catch (Exception ex) { } } var temp = insertedDrives.ToArray(); foreach (var v in temp) { if (!drives.Select(x => x.Name).Contains(v.Name)) { removedEvent(v.Name); insertedDrives.Remove(v); } } if (stopCommand) break; Thread.Sleep(ScanningInterval); } })); }
private void WatcherOnEventArrived(object sender, EventArrivedEventArgs e) { string driveName = e.NewEvent.Properties["DriveName"].Value.ToString(); DriveEventType eventType = (DriveEventType)Convert.ToInt16(e.NewEvent.Properties["EventType"].Value); if (eventType == DriveEventType.Inserted) { DriveInsertedEvent?.Invoke(this, driveName); } else if (eventType == DriveEventType.Removed) { DriveRemovedEvent?.Invoke(this, driveName); } }