@bobnoordam

Enumerating available performance counters on local and remote systems using C#

Performance counters

Perfmon, the well known tool for monitoring performance counters has a nice list of categories and counters for your system. But what if you want to access a counter from code ? Or even worse, want to check if a certain counter is available or not ?

In the previous document Collecting performance data from local and remote systems using C# i provided you with a simple class to query performance data on local and remote machines. The class below provides you with the funcationlity to query the list of categories, and the counters for each category. Like in the previous example, this can be run against your local, and against remote machines.

Dumping it all to the console

This little piece of code uses our worker class to enumerate everything it can find, and dump it all to the console. Replace the hostname in this sample (“S30”) with your local or remote computername that you want to analyze. Keep in mind that for enumerating remote systems you need to be part of the Performance monitor users on that system.

var mgr = new CounterEnumerator("S30");
List<string> cats = mgr.GetCategories();
foreach(string s in cats) {
    Console.WriteLine("counters for: " + s);
    List<string> counters = mgr.getCounters(s);
    foreach(string t in counters) {
        Console.WriteLine("\t" + t);
    }
}

The worker class

using System.Collections.Generic;


namespace ConsoleApp1
{
    class CounterEnumerator
    {
        private string _machine;
        public CounterEnumerator(string machine) {
            _machine = machine;
        }

        /// <summary>
        /// Returns a list of categories present on the given machine
        /// </summary>
        /// <returns></returns>
        public List<string> GetCategories() {
            var catlist = System.Diagnostics.PerformanceCounterCategory.GetCategories(_machine);
            var result = new List<string>();
            foreach(var x in catlist) {
                result.Add(x.CategoryName);
            }
            return result;
        }

        /// <summary>
        /// Resturns a list of performance counters in the given categorie
        /// </summary>
        /// <param name="categorie"></param>
        /// <returns></returns>
        public List<string> getCounters(string categorie) {
            List<string> result = new List<string>();
            var manager = new System.Diagnostics.PerformanceCounterCategory(categorie, _machine);
            var instances = manager.GetInstanceNames();
            foreach(string i in instances) {
                var counters = manager.GetCounters(i);
                foreach (var x in counters) {
                    result.Add(x.CounterName);
                }
            }
            return result;
        }

    }
}