微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 如何监控特定应用程序的网络带宽使用情况?

我正在尝试学习如何监视特定应用程序的网络带宽使用情况.我正在看IPv4InterfaceStatistics,但这似乎监控了NIC卡的性能.
我想监视一个特定的应用程序,看看每秒消耗多少带宽.
有谁知道如何做到这一点的例子?

解决方法

using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.sockets;
using System.Reflection;
using System.Text;
using System.Threading;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                var bytesSentPerformanceCounter = new PerformanceCounter();
                bytesSentPerformanceCounter.CategoryName = ".NET CLR Networking";
                bytesSentPerformanceCounter.CounterName = "Bytes Sent";
                bytesSentPerformanceCounter.InstanceName = GetInstanceName();
                bytesSentPerformanceCounter.ReadOnly = true;

                var bytesReceivedPerformanceCounter = new PerformanceCounter();
                bytesReceivedPerformanceCounter.CategoryName = ".NET CLR Networking";
                bytesReceivedPerformanceCounter.CounterName = "Bytes Received";
                bytesReceivedPerformanceCounter.InstanceName = GetInstanceName();
                bytesReceivedPerformanceCounter.ReadOnly = true;

                Console.WriteLine("Bytes sent: {0}",bytesSentPerformanceCounter.RawValue);
                Console.WriteLine("Bytes received: {0}",bytesReceivedPerformanceCounter.RawValue);
                Thread.Sleep(1000);
            }
        }

        private static string GetInstanceName()
        {
            string returnvalue = "not found";
          //Checks bandwidth usage for CUPC.exe..Change it with your application Name
            string applicationName = "CUPC"; 
                PerformanceCounterCategory[] Array = PerformanceCounterCategory.GetCategories();
            for (int i = 0; i < Array.Length; i++)
            {
                if (Array[i].CategoryName.Contains(".NET CLR Networking"))
                    foreach (var item in Array[i].GetInstanceNames())
                    {
                        if (item.ToLower().Contains(applicationName.ToString().ToLower()))
                            returnvalue = item;

                    }

            }
            return returnvalue;
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐