Search code examples
c#.netiodiskperformancecounter

Determine total amount of disk I/O read and write data (in bytes) for specified process in C#?


I would like to determine the total amount of disk I/O read data and also write data (in bytes) for a specific process.

Not sure if this can be done through performance counters, because when I run this code example from MSDN I only see these related counter names which does not seem to be able retrieve the information that I need since they are in data/sec which seems to serve for calculating an average value only...

  • IO Read Operations/sec
  • IO Write Operations/sec
  • IO Data Operations/sec
  • IO Other Operations/sec
  • IO Read Bytes/sec
  • IO Write Bytes/sec
  • IO Data Bytes/sec
  • IO Other Bytes/sec

In case of I'm wrong, then please explain me which of those counters I need to use and how do I need to compare their values (using PerformanceCounter.NextValue() or PerformanceCounter.NextSample() + CounterSample.Calculate()).

I know this information can be retrieved by some task managers such as System Explorer:

enter image description here

I just would like to do the same.


Solution

  • GetProcessIoCounters() is an concise alternative to Perf counters/WMI.

    struct IO_COUNTERS {
        public ulong ReadOperationCount;
        public ulong WriteOperationCount;
        public ulong OtherOperationCount;
        public ulong ReadTransferCount;
        public ulong WriteTransferCount;
        public ulong OtherTransferCount;
    }
    
    ...
    
    [DllImport(@"kernel32.dll", SetLastError = true)]
    static extern bool GetProcessIoCounters(IntPtr hProcess, out IO_COUNTERS counters);
    
    ...
    
    if (GetProcessIoCounters(Process.GetCurrentProcess().Handle, out IO_COUNTERS counters)) {
        Console.WriteLine(counters.ReadOperationCount);
        ...