How To Retrive Collections Of Management Objects
The following code example uses the System.Management collection classes to enumerate environment variables on a computer. Some parameters can be left to default values in this example because the example gets information from the local computer. The managementscope class will be used if the information gets from romoting computer.
There are tow way to demostrate how to enumerate the collection of 'win32_environment'.
Synchronous way:
public void DoSynchronous()
{
//SelectQuery is inherited from ManagementQuery.
//The description about ManagementQuery in chapter 1
//The description about ManagementQuery in chapter 1
SelectQuery query = new SelectQuery("WIN32_Environment");
ManagementObjectSearcher mObjSearch = new ManagementObjectSearcher(query);
int count = mObjSearch.Get().Count;
//ManagementBaseObect is inherited from ManagementObject;
foreach (ManagementBaseObject item in mObjSearch.Get())
{
textBox1.Text += //string.Concat("classPath", item.ClassPath.Path) + System.Environment.NewLine +
//string.Concat("ClassName", item.ClassPath.ClassName) +
System.Environment.NewLine + string.Concat("Name", item["Name"]).PadRight(5, ' ') +
string.Concat("Value", item["VariableValue"])
+ System.Environment.NewLine;
}
foreach (ManagementBaseObject item in mObjSearch.Get())
{
textBox1.Text += //string.Concat("classPath", item.ClassPath.Path) + System.Environment.NewLine +
//string.Concat("ClassName", item.ClassPath.ClassName) +
System.Environment.NewLine + string.Concat("Name", item["Name"]).PadRight(5, ' ') +
string.Concat("Value", item["VariableValue"])
+ System.Environment.NewLine;
}
}
Asynchronous way:
ManagementObjectSearcher mObjSearch = new ManagementObjectSearcher(new SelectQuery("WIN32_Service"));
ManagementOperationObserver mOperObserver = new ManagementOperationObserver();
mOperObserver.ObjectReady += new ObjectReadyEventHandler(mOperObserver_ObjectReady);
mOperObserver.Completed += new CompletedEventHandler(mOperObserver_Completed);
mObjSearch.Get(mOperObserver);
本文转自lidup 51CTO博客,原文链接:http://blog.51cto.com/lidup/325289,如需转载请自行联系原作者