简体   繁体   English

WMI查询-System.Management.ManagementException

[英]WMI Query - System.Management.ManagementException

I'm getting some errors that I don't really understand. 我遇到了一些我不太了解的错误。 I'm hoping someone can help me. 我希望有人能帮助我。

The first exception I get is System.Management.ManagementException on the 'in' in my foreach. 我得到的第一个异常是foreach中“ in”上的System.Management.ManagementException

The next is an index out of range on 'device'. 下一个是“设备”上的索引超出范围。 What really confuses me is that this worked when it didn't accept variables passed into it. 真正令我困惑的是,当它不接受传递给它的变量时,它起作用了。 When I re factored it to make it more flexible it broke. 当我重新分解它以使其更灵活时,它坏了。

Can someone point me in the right direction? 有人可以指出我正确的方向吗?

Property and win32Class are passed in from the main program into this class 属性和win32Class从主程序传递到此类中

Here's what and how I'm passing 这是我过去的方式和方式

    static void Main(string[] args)
    {
        GatherSystemINfoWMI.GetPropertyValue("name", "Win32_CDROMDrive");
    }

// Here's what I'm passing it to //这就是我要传递给的内容

       public static void GetPropertyValue(string property, string win32Class)
    {

        ManagementObjectSearcher searcher =
      new ManagementObjectSearcher("Select " + property + "from " + win32Class);
        foreach (ManagementObject device in searcher.Get())
        {
            Console.WriteLine("Name: {0} ",
                          device.GetPropertyValue("Name"));
            Console.WriteLine(device.GetPropertyValue(property) + "\n");
            Console.ReadKey();
        }

Add a space in the "from " part of your sql: 在SQL的“ from”部分添加一个空格:

Replace 更换

"Select " + property + "from " + win32Class

with

"Select " + property + " from " + win32Class

Or better use string.Format() : 或更好地使用string.Format()

string query = string.Format("Select {0} from {1}", property, win32Class);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM