Retrieve process network usage

前端 未结 3 1753
孤街浪徒
孤街浪徒 2020-12-02 13:35

How can I get a process send/receive bytes? the preferred way is doing it with C#.

I\'ve searched this a lot and I didn\'t find any simple solution for this. Some so

3条回答
  •  抹茶落季
    2020-12-02 14:28

    You can use PerformanceCounter. Sample code:

    //Define 
    string pn = "MyProcessName.exe";
    var readOpSec  = new PerformanceCounter("Process","IO Read Operations/sec", pn);
    var writeOpSec = new PerformanceCounter("Process","IO Write Operations/sec", pn);
    var dataOpSec  = new PerformanceCounter("Process","IO Data Operations/sec", pn);
    var readBytesSec = new PerformanceCounter("Process","IO Read Bytes/sec", pn);
    var writeByteSec = new PerformanceCounter("Process","IO Write Bytes/sec", pn);
    var dataBytesSec = new PerformanceCounter("Process","IO Data Bytes/sec", pn);
    
    var counters = new List
                    {
                    readOpSec,
                    writeOpSec,
                    dataOpSec,
                    readBytesSec,
                    writeByteSec,
                    dataBytesSec
                    };
    
    // get current value
    foreach (PerformanceCounter counter in counters)
    {
        float rawValue = counter.NextValue();
    
        // display the value
    }
    

    And this is to get performance counters for the Network card. Note it is not process specific

    string cn = "get connection string from WMI";
    
    var networkBytesSent = new PerformanceCounter("Network Interface", "Bytes Sent/sec", cn);
    var networkBytesReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", cn);
    var networkBytesTotal = new PerformanceCounter("Network Interface", "Bytes Total/sec", cn);
    
    Counters.Add(networkBytesSent);
    Counters.Add(networkBytesReceived);
    Counters.Add(networkBytesTotal);
    

提交回复
热议问题