Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Error in using WMI to catch logical drives events

Discussion in 'Scripting' started by AzeExMachina, May 21, 2019.

  1. AzeExMachina

    AzeExMachina

    Joined:
    Jan 30, 2016
    Posts:
    14
    Hi everyone, I'm trying to catch Win32 events to detect plugged in drives such as usb and external hard disks. I've imported the System.Management.dll from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\ and then wrote the script like this

    Code (CSharp):
    1.  var watcher = new ManagementEventWatcher();
    2. var query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent");
    3. watcher.EventArrived += (s, e) =>
    4. {
    5.          //log event properties
    6. };
    7. watcher.Query = query;
    8. watcher.Start();
    However, this raises an error when the thread starts:
    Code (CSharp):
    1.  NullReferenceException: Object reference not set to an instance of an object
    2. System.Management.ThreadDispatch.Start () (at <a2edda3557ef4ca8b6e3156a8719c2a2>:0)
    3. System.Management.ManagementScope.Initialize () (at <a2edda3557ef4ca8b6e3156a8719c2a2>:0)
    4. System.Management.ManagementObjectSearcher.Initialize () (at <a2edda3557ef4ca8b6e3156a8719c2a2>:0)
    5. System.Management.ManagementObjectSearcher.Get () (at <a2edda3557ef4ca8b6e3156a8719c2a2>:0)
    Does anyone have any experience with this? The same code works when inside a simple console application or inside a windows service
     
  2. VertigoJack

    VertigoJack

    Joined:
    Aug 2, 2019
    Posts:
    8
    2 years later and I'm still having this exact same issue... I would love to know if this is just an engine limitation or not.
     
  3. HummeL_AL

    HummeL_AL

    Joined:
    May 31, 2019
    Posts:
    10
    After another 2 years, I also encountered this problem, but in a slightly different use case:
    Code (CSharp):
    1.  
    2.         ManagementObjectSearcher searcher =
    3.         new ManagementObjectSearcher("root\\CIMV2",
    4.         "SELECT * FROM Win32_PnPEntity");
    5.         foreach ( ManagementObject queryObj in searcher.Get( ) ) {
    6.             Debug.Log( $"Device id: {queryObj[ "DeviceID" ]}\nPNPDeviceID: {queryObj[ "PNPDeviceID" ]}\nName: {queryObj[ "Name" ]}" );
    7.         }