Question

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.

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

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();
        }
Was it helpful?

Solution

Add a space in the "from " part of your sql:

Replace

"Select " + property + "from " + win32Class

with

"Select " + property + " from " + win32Class

Or better use string.Format():

string query = string.Format("Select {0} from {1}", property, win32Class);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top