27 Jan
Wrestled with this for a while.. here’s how I got it.
using System.Management;
ManagementScope mgmtScope;
if(MachineName != Environment.MachineName)
{
ConnectionOptions options = new ConnectionOptions();
options.Username = AdminUser;
options.Password = AdminPass;
mgmtScope = new ManagementScope(@"\\" + MachineName + @"\root\cimv2",options);
}
else
{
mgmtScope = new ManagementScope(@"\\.\root\cimv2");
}
try
{
mgmtScope.Connect();
}
catch(Exception ex){...}
ManagementPath mp = new ManagementPath("Win32_Processor");
try
{
ManagementClass mc = new ManagementClass(mgmtScope, mp, null);
ManagementObjectCollection procs = mc.GetInstances();
foreach(ManagementObject mo in procs)
{
string DeviceID = "";
string Usage = "";
foreach(PropertyData pd in mo.Properties)
{
if(pd.Name == "DeviceID")
DeviceID = pd.Value.ToString();
if(pd.Name == "LoadPercentage")
Usage = pd.Value.ToString();
}
Perf_Processors.Add(DeviceID, Usage);//A Hashtable I'm using to store the info
}
}
catch(Exception ex){...}
2 Responses for "CPU load percentage in C# and .Net"
Wich version of .NET are you using? 1.1 does not contain System.Management.
I was using .Net 1.1. But I believe you need to add the System.Management namespace to your references.
Leave a reply