PerformanceCounter to monitor your system

At C#. there is a useful method in order to monitor the system like RAM and CPU Usage in percent using using the System.Diagnostics.PerformanceCounter class

in the following post, I will demonstrate one of implementation into a console application.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Globalization;
using System.IO;
namespace CheckCPUUsage
{
class Program
{
protected static PerformanceCounter cpuCounter;
// protected static PerformanceCounter ramCounter;
static void Main(string[] args)
{
string path;
if (args.Length < 2)
{
if (args.Length < 1)
{
return;
}
path = string.Format(CultureInfo.CurrentCulture, “LogCPU_{0:yyyyMMdd}.xls”, DateTime.Now);
}
else
{
path = args[1];
}
string machine = args[0];
Console.WriteLine(machine);
try
{
cpuCounter = new PerformanceCounter(“Processor”, “% Processor Time”, “_Total”, machine);
// ramCounter = new PerformanceCounter(“Memory”, “Available MBytes”,””,machine);
while (true)
{
System.IO.StreamWriter file = System.IO.File.AppendText(path);
file.WriteLine(string.Format(CultureInfo.CurrentCulture, “{0}\t{1}\t{2}”, DateTime.Now, cpuCounter.NextValue(), “”));
file.Close();
Console.WriteLine(cpuCounter.NextValue() + “% “);// + ramCounter.NextValue() + “MB”);
Thread.Sleep(1000);
}
}
catch (System.Security.SecurityException securityException)
{
Console.WriteLine(securityException.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}