Exemplo n.º 1
0
        static SDService()
        {
            Validator = DefaultValidator;

            // Create an event handler to detect when a drive is added or removed
            Watcher = new ManagementEventWatcher();
            WqlEventQuery query = new WqlEventQuery("SELECT * FROM __InstanceOperationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_LogicalDisk' AND TargetInstance.Description = \"Removable disk\"");

            Watcher.EventArrived += new EventArrivedEventHandler((s, e) =>
            {
                string driveName             = ((ManagementBaseObject)e.NewEvent["TargetInstance"]).Properties["DeviceID"].Value.ToString();
                DriveInfo actedDrive         = new DriveInfo(driveName);
                DirectoryInfo actedDriveRoot = FindRootForSd(actedDrive);

                if (actedDrive.IsReady)
                {
                    if (CurrentDrive != null && CurrentDrive.Name == actedDrive.Name)
                    {
                        OnSDRemoved?.Invoke(SDEffectiveRoot);
                    }

                    if (Validator(actedDriveRoot))
                    {
                        CurrentDrive    = actedDrive; // set current drive so the event handler *could* access it directly, but why tho
                        SDRoot          = CurrentDrive.RootDirectory;
                        SDEffectiveRoot = actedDriveRoot;
                        OnSDPluggedIn?.Invoke(SDEffectiveRoot);
                    }
                }
                else if (CurrentDrive != null) // if a drive hasn't been found to begin with, no need to check what was removed
                {
                    DirectoryInfo currentDrive = new DirectoryInfo(CurrentDrive.Name);
                    if (currentDrive.Name == actedDrive.Name) // was the removed drive the one we found?
                    {
                        OnSDRemoved?.Invoke(SDEffectiveRoot); // Allow the handler read the current drive before we clear it
                        CurrentDrive    = null;
                        SDRoot          = null;
                        SDEffectiveRoot = null;
                    }
                }
            });
            Watcher.Query = query;
        }
Exemplo n.º 2
0
        public static void ResetHandlers()
        {
            // Clear event handlers
            if (OnSDPluggedIn != null)
            {
                foreach (Delegate d in OnSDPluggedIn.GetInvocationList())
                {
                    OnSDPluggedIn -= (SDChangedEventHandler)d;
                }
            }
            if (OnSDRemoved != null)
            {
                foreach (Delegate d in OnSDRemoved.GetInvocationList())
                {
                    OnSDRemoved -= (SDChangedEventHandler)d;
                }
            }

            // Reset validator to default
            Validator = DefaultValidator;
        }