C# 如何在C中显示每秒接收的字节数#

C# 如何在C中显示每秒接收的字节数#,c#,networking,byte,performancecounter,C#,Networking,Byte,Performancecounter,我试图每秒显示接收到的字节,并让它们每秒在控制台中显示一次。当I达到.nextvalue时,它将显示一个无效的操作异常 PerformanceCounter NetworkDownSpeed = new PerformanceCounter("Network Interface", "Bytes Received/sec"); float CurrentNetworkDownSpeed = (int)NetworkDownSpeed.NextValue(); while (true) {

我试图每秒显示接收到的字节,并让它们每秒在控制台中显示一次。当I达到.nextvalue时,它将显示一个无效的操作异常

PerformanceCounter NetworkDownSpeed = new PerformanceCounter("Network Interface", "Bytes Received/sec");
float CurrentNetworkDownSpeed = (int)NetworkDownSpeed.NextValue();

while (true)
{
    Console.WriteLine("Current Network Download Speed: {0}MB", CurrentNetworkDownSpeed);
    Thread.Sleep(1000);
}
NetworkDownSpeed.NextValue()可以引发InvalidOperationException

其中有一条评论详细说明了原因

// If the category does not exist, create the category and exit.
// Performance counters should not be created and immediately used.
// There is a latency time to enable the counters, they should be created
// prior to executing the application that uses the counters.
// Execute this sample a second time to use the category.

您可以在此

上找到解决此问题的替代解决方案。很抱歉,有人已经回答了,但这有帮助吗

private static void ShowNetworkTraffic()
{
    PerformanceCounterCategory performanceCounterCategory = new PerformanceCounterCategory("Network Interface");
    string instance = performanceCounterCategory.GetInstanceNames()[0]; // 1st NIC !
    PerformanceCounter performanceCounterSent = new PerformanceCounter("Network Interface", "Bytes Sent/sec", instance);
    PerformanceCounter performanceCounterReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", instance);

    for (int i = 0; i < 10; i++)
    {
        Console.WriteLine("bytes sent: {0}k\tbytes received: {1}k", performanceCounterSent.NextValue() / 1024, performanceCounterReceived.NextValue() / 1024);
        Thread.Sleep(500);
    }
}
private static void ShowNetworkTraffic()
{
PerformanceCounterCategory PerformanceCounterCategory=新的PerformanceCounterCategory(“网络接口”);
string instance=performanceCounterCategory.GetInstanceNames()[0];//第一个NIC!
PerformanceCounter performanceCounterSent=新的PerformanceCounter(“网络接口”,“每秒发送的字节数”,实例);
PerformanceCounter performanceCounterReceived=新的PerformanceCounter(“网络接口”,“接收字节/秒”,实例);
对于(int i=0;i<10;i++)
{
WriteLine(“发送字节:{0}k\t接收字节:{1}k”,performanceCounterSent.NextValue()/1024,performanceCounterReceived.NextValue()/1024);
睡眠(500);
}
}

从。

您能定义“代码中断”吗?我看到一个对话框,显示一个无效的操作异常。要读取性能计数器,您必须具有管理权限。在Windows Vista中,(UAC)确定用户的权限。如果您是内置Administrators组的成员,则会为您分配两个运行时访问令牌:标准用户访问令牌和管理员访问令牌。默认情况下,您处于标准用户角色。若要执行访问性能计数器的代码,必须首先提升您的权限om标准用户对管理员。“不以管理员身份运行将产生
未经授权的访问异常
。如果您可以验证您是以管理员身份运行的,或者您遇到了什么异常,我们可以进一步提供帮助,但这是最大的问题。编辑:如果您收到
invalidoOperationException
,则您尚未正确设置性能计数器,请参阅我链接的页面。感谢您共享该链接。我可以确认我正在以系统管理员的身份运行。我已经尝试将性能计数器更改为“内存”、“可用MB”,这会使代码运行。网络值的处理方式是否不同?