'Sessions count to IIS site Web server using C#

Currently, I am working on a requirement to find Current Anonymous Users and Current Connections (sessions) count for IIS Web Server in C#.

I have written the following code in C# using PerformanceCounter, but the output of this code is always zero.

var anonymousUsers = new PerformanceCounter();
                anonymousUsers.MachineName = Environment.MachineName;
                anonymousUsers.CategoryName = "Web Service";
                anonymousUsers.CounterName = "Current Anonymous Users";
                anonymousUsers.InstanceName = "_Total";

                var firstValue = anonymousUsers.NextValue();
                Thread.Sleep(500);
                var secondValue = (int)anonymousUsers.NextValue();
                Console.WriteLine($"Current Anonymous Users Count is:{secondValue}");
                
                var cc = new PerformanceCounter();
                cc.MachineName = Environment.MachineName;
                cc.CategoryName = "Web Service";
                cc.CounterName = "Current Connections";
                cc.InstanceName = "_Total";

                var firstValu1e = cc.NextValue();
                Thread.Sleep(500);
                var secondValue1 = (int)cc.NextValue();
                Console.WriteLine($"Current Connections Count is:{secondValue1}");

Anyone can tell me? What is the issue?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source