Using ManagementObject to retrieve a single WMI property
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 (ManagementObjec开发者_JAVA技巧t 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?
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"]);
精彩评论