4

启动 MaagementEventWatcher 时有时未找到异常

我的代码示例如下:

 try
        {
            string scopePath = @"\\.\root\default";
            ManagementScope managementScope = new ManagementScope(scopePath);
            WqlEventQuery query =
                new WqlEventQuery(
                    "SELECT * FROM RegistryKeyChangeEvent WHERE " + "Hive = 'HKEY_LOCAL_MACHINE'"
                    + @"AND KeyPath = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'");
            registryWatcher = new ManagementEventWatcher(managementScope, query);
            registryWatcher.EventArrived += new EventArrivedEventHandler(SerialCommRegistryUpdated);

            registryWatcher.Start();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            if (registryWatcher != null)
            {
                registryWatcher.Stop();
            }
        }

例外:

  Not found
  at System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode)
  at System.Management.ManagementEventWatcher.Start()
  at MTTS.LabX.RockLog.AppService.USBMonitor.AddRegistryWatcherHandler()]

注意:我检查了注册表,找到了文件夹和文件。

4

2 回答 2

2

当 WQL 查询中没有匹配项时,抛出 ManagementException“未找到”。也许您指定了错误的 KeyPath 或 KeyPath 不再可用。

于 2013-04-26T09:40:07.267 回答
2

实际上问题是,在笔记本电脑(具有串行端口的电脑,所以 COM1 端口)中,第一次启动时没有在注册表中创建 SERIALCOMM 文件夹,因为,

基本上我们将设备插入 SERIALCOMM 文件夹将创建的 USB 端口或串行端口,在这种情况下,我们使用 WMI 从注册表中获取连接的通信端口。

在某些笔记本电脑中,没有连接 USB 端口和串行端口因此,未创建 SERIALCOMM 文件夹,那时我们正在访问此注册表路径,我们会收到错误消息。

所以解决方案是,

try
            {
                string scopePath = @"\\.\root\default";
                ManagementScope managementScope = new ManagementScope(scopePath);

                string subkey = "HARDWARE\\DEVICEMAP\\SERIALCOMM";

                using (RegistryKey prodx = Registry.LocalMachine)
                {
                    prodx.CreateSubKey(subkey);
                }

                WqlEventQuery query = new WqlEventQuery(
                    "SELECT * FROM RegistryKeyChangeEvent WHERE " +
                   "Hive = 'HKEY_LOCAL_MACHINE'" +
                  @"AND KeyPath = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'");

                registryWatcher = new ManagementEventWatcher(managementScope, query);

                registryWatcher.EventArrived += new EventArrivedEventHandler(SerialCommRegistryUpdated);
                registryWatcher.Start();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                if (registryWatcher != null)
                {
                    registryWatcher.Stop();
                }
            }
于 2013-05-08T07:36:16.800 回答