Fetching Application-Specific Network Traffic Metrics (Bytes/Sec) Using C# and Windows Resource Monitor

51 Views Asked by At

I am attempting to retrieve the received Bytes per second as observed in the Windows Resource Monitor under "Network." The information I am interested in pertains to a specific application (such as msedge.exe), and I want to obtain it exclusively for the specified IP address.

I attempted to fetch the necessary data using the following code:

            var processId = Process.GetProcessesByName("msedge").FirstOrDefault()?.Id;

            if (processId.HasValue)
            {
                using (var session = new TraceEventSession("MyKernelAndClrEventsSession"))
                {
                    session.EnableKernelProvider(KernelTraceEventParser.Keywords.NetworkTCPIP);

                    long receivedBytes = 0;
                    long sentBytes = 0;

                    session.Source.Kernel.TcpIpRecv += data =>
                    {
                        if (data.ProcessID == processId)
                        {
                            receivedBytes += data.size;
                        }
                    };

                    session.Source.Kernel.TcpIpSend += data =>
                    {
                        if (data.ProcessID == processId)
                        {
                            sentBytes += data.size;
                        }
                    };

                    session.Source.Process();

                    Console.WriteLine($"Bytes Received: {receivedBytes}");
                    Console.WriteLine($"Bytes Sent: {sentBytes}");
                }
            }
            else
            {
                Console.WriteLine("msedge.exe is not running.");
            }

However, it consistently displayed 0 for some reason.

The IP I am attempting to filter by is a static IP from my local network.

Is there a way (even using third-party libraries) to fulfill my requirement? It appears that System.Diagnostics might not be sufficient.

Thanks in advance.

0

There are 0 best solutions below