Exemple #1
0
        /// <summary>
        /// Обработчик события вставки/удаления флешки
        /// </summary>
        private void USBEventArrived_Creation(object sender, EventArrivedEventArgs e)
        {
            string driveLetter = (string)e.NewEvent.Properties["DriveName"].Value;
            ushort eventType   = (ushort)e.NewEvent.Properties["EventType"].Value;
            var    entry       = new UsbStateEntry {
                DriveLetter = driveLetter
            };

            FillLogEntry(entry, null);

            // Вставили
            if (eventType == 2)
            {
                Console.WriteLine("Added: " + driveLetter);
                entry.State = USB_STATE.INSERTED;
                // Пытаемся получить серийник 9 раз по 333 мс
                for (int i = 0; i < 9; ++i)
                {
                    entry.SerialNumber = GetVolumeSerialNumberByName(driveLetter);
                    if (entry.SerialNumber != null)
                    {
                        break;
                    }
                    // Retry 9 times
                    Thread.Sleep(333);
                }
                CheckAttachedUsb(driveLetter, entry.SerialNumber);
                AddEntryToDatabase(entry);
                // Удалили
            }
            else if (eventType == 3)
            {
                Console.WriteLine("Removed: " + driveLetter);
                entry.State = USB_STATE.REMOVED;
                UnregisterHandle(driveLetter);
                FileSystemWatcher fsw;
                _fswMap.TryGetValue(driveLetter, out fsw);
                if (fsw != null)
                {
                    fsw.EnableRaisingEvents = false;
                    _fswMap.Remove(driveLetter);
                }

                string oldSerial;
                if (_letterToSerialMap.TryGetValue(driveLetter, out oldSerial))
                {
                    _letterToSerialMap.Remove(driveLetter);
                    entry.SerialNumber = oldSerial;
                }
                AddEntryToDatabase(entry);
            }
        }
Exemple #2
0
 /// <summary>
 /// Проверяем есть ли у пользователя доступ к флешке и есть есть, то устанавливаем слежку за файлами
 /// Если нет, то отключаем флешку
 /// </summary>
 private void CheckAttachedUsb(string driveLetter, string serial)
 {
     _letterToSerialMap.Add(driveLetter, serial);
     if (IsUsbAllowed(serial))
     {
         RegisterForHandle(driveLetter);
         AddNewFSWatcher(driveLetter);
     }
     else
     {
         Console.WriteLine("REJECTED for {0}", serial);
         var entry = new UsbStateEntry {
             DriveLetter  = driveLetter,
             State        = USB_STATE.REJECTED,
             SerialNumber = serial
         };
         FillLogEntry(entry, serial);
         AddEntryToDatabase(entry);
         DetachUsb(driveLetter);
     }
 }