Using ManagementObject to Get One WMI Property

This is probably not the best way, but I am currently amassing the amount of RAM on the machine using:

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

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

This works well and well, but I feel like I can do it more directly and without using foreach on a single element, but I cannot figure out how to index 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 figure it out. Any ideas?

+2


a source to share


1 answer


The foreach statement hides the counter you want. 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"]);

      

+3


a source







All Articles