未找到异常启动ManagementEventWatcher时

时间:2013-04-25 10:39:27

标签: c#-4.0 service managementeventwatcher

在启动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()]

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

2 个答案:

答案 0 :(得分:2)

当WQL查询中不匹配时,抛出ManagementException“Not found”。可能您指定了错误的KeyPath或KeyPath不再可用。

答案 1 :(得分: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();
                }
            }