Search code examples
c#performancecounter

In c# how to get given disk's realtime "Active time" in%, "Average response time"?


Been trying to get this work but I just couldn't get the exact solution

PerformanceCounter disk = new PerformanceCounter("LogicalDisk", "% Disk Time", @"F:");
//disk.NextValue(); <------but this doesn't give me exact Active time% 

enter image description here


Solution

  • From the link HansPassant sent me, I developed a code and now it works perfect.

     string instanceName = "F:";
            string query = $"SELECT * FROM Win32_PerfFormattedData_PerfDisk_LogicalDisk WHERE Name = '{instanceName}'";
            foreach (ManagementBaseObject result in new ManagementObjectSearcher(query).Get())
            {
                Console.WriteLine("Disk usage: {0}%",  100-Convert.ToInt32(result["PercentIdleTime"]));
            }
    

    Another solution to my previous code is to simply use "% Idle Time" in counterName paramter.

        PerformanceCounter counter = new PerformanceCounter("LogicalDisk", "% Idle Time", "F:");
    Console.WriteLine("Disk idle time: {0}%", 100-(int)counter.NextValue());