In the old days you had to use COM to access WMI but since .Net 2.0, Microsoft have provided WMI extensions that are built-in to the .Net framework these days. This is much easier to use
so I would recommend that approach.
Firstly, your project needs reference to System.Management
Each provider needs to be decorated with the following assembly attribute:
[assembly: WmiConfiguration(@"root\MyApplication",
HostingModel = ManagementHostingModel.Decoupled)]As you can see, I provide my "namespace" I am going to use for my WMI instances as well as specifying a hosting model. A decoupled hosting model is an in-process hosting model.To inform the WMI infrastructure that the assembly contains a WMI provider, the assembly must contain an installer class that can be run by the InstallUtil.exe command.
This installer class must derive from the DefaultManagementInstaller class and be decorated
with the [RunInstaller] attribute. It does not require any additional functionality.
[RunInstaller(true)]
public class WMISampleLibraryInstaller :
DefaultManagementInstaller { }
You can use InstallUtil in the Visual Studio Command prompt with the following line:
InstallUtil MyAssembly.dll
Read-Only Information
The most rudimentary kind of WMI provider is a WMI provider that exposes
read-only information regarding a configurable entity.
[ManagementEntity]
public class ProcessInformation
{
Process _theProcess;
[ManagementBind]
public ProcessInformation(
[ManagementName("Id")] int id)
{
_theProcess = Process.GetProcessById(id);
}
[ManagementKey]
public int Id
{
get { return _theProcess.Id; }
}
[ManagementProbe]
public int ThreadCount
{
get { return _theProcess.Threads.Count; }
}
}
To publish the instance to the WMI infrastructure, the hosting process can use the following code:foreach (Process p in Process.GetProcesses())
{
InstrumentationManager.Publish(
new ProcessInformation(p.Id));
}
You can query information on WMI with the following query:
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(@"root\MyApplication",
"SELECT * FROM ProcessInformation");
foreach (ManagementObject obj in searcher.Get())
Console.WriteLine("Id: " + obj["Id"] +
", ThreadCount: " + obj["ThreadCount"]);
There are similar tasks you can do for Write Properties and Methods. These are just different attributes you have to use. There is a limitation that Singletons cannot be used for Write Properties and Methods.
You use [ManagementTask] attribute on a method to expose it through WMI.
You use [ManagementConfiguration] attribute on a write property to expose it through WMI.
