tags:

views:

253

answers:

1

This probably isn't the best way, but I am currently retrieving the amount of RAM on a machine using:

manageObjSearch.Query = new ObjectQuery("SELECT TotalVisibleMemorySize FROM Win32_OperatingSystem");
manageObjCol = manageObjSearch.Get();

foreach (ManagementObject mo in manageObjCol)
 sizeInKilobytes = Convert.ToInt64(mo["TotalVisibleMemorySize"]);

It works well and good, but I feel I could be doing this more directly and without a foreach over a single element, but I can't figure out how to index a ManagementObjectCollection

I want to do something like this:

ManagementObject mo = new ManagementObject("Win32_OperatingSystem.TotalVisibleMemorySize")
mo.Get();

Console.WriteLine(mo["TotalVisibleMemorySize"].ToString())

or maybe even something like

ManagementClass mc = new ManagementClass("Win32_OperatingSystem");
Console.WriteLine(mc.GetPropertyValue("TotalVisibleMemorySize").ToString());

I just can't seem to figure it out. Any ideas?

+1  A: 

The foreach statement is hiding the enumerator you need to access. You can do it directly like this:

        var enu = manageObjSearch.Get().GetEnumerator();
        if (!enu.MoveNext()) throw new Exception("Unexpected WMI query failure");
        long sizeInKilobytes = Convert.ToInt64(enu.Current["TotalVisibleMemorySize"]);
Hans Passant
Thanks for the help, Hans.
Jesse
Also, starting with Vista, Win32_OPeratingSystem is a singleton class so you can avoid using ManagementObjectSearcher. See here:http://stackoverflow.com/questions/56208/wmi-directly-accessing-the-singleton-instance-of-win32-operatingsystem/73054#73054
Uros Calakovic