C#获取系统网络使用情况

San*_*sal 11 c# networking

我需要一种方法来获得当前系统网络的使用,上下.

我在网上找到了一些,但他们没有为我工作.

谢谢你的帮助

代码段:


 private void timerPerf_Tick(object sender, EventArgs e)
        {
            if (!NetworkInterface.GetIsNetworkAvailable())
                return;

            NetworkInterface[] interfaces
                = NetworkInterface.GetAllNetworkInterfaces();

            foreach (NetworkInterface ni in interfaces)
            {
                this.labelnetup.Text = "    Bytes Sent: " + ni.GetIPv4Statistics().BytesSent;
                this.labelnetdown.Text = "    Bytes Rec: " + ni.GetIPv4Statistics().BytesReceived;
            }

        }
Run Code Online (Sandbox Code Playgroud)

And*_*are 25

请参阅NetworkInterface的报告信息:网络统计信息,以获得一个好的示例程序:

using System;
using System.Net.NetworkInformation;

class MainClass
{
    static void Main()
    {
        if (!NetworkInterface.GetIsNetworkAvailable())
           return;

        NetworkInterface[] interfaces 
            = NetworkInterface.GetAllNetworkInterfaces();

        foreach (NetworkInterface ni in interfaces)
        {                
            Console.WriteLine("    Bytes Sent: {0}", 
                ni.GetIPv4Statistics().BytesSent);
            Console.WriteLine("    Bytes Received: {0}",
                ni.GetIPv4Statistics().BytesReceived);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 不,它一直返回0,我尝试设置下载,但数字没有变化. (3认同)

小智 5

您也可以通过使用 PerformanceCounterCategory 来获取当前系统的网络使用情况:

using System;
using System.Diagnostics;

class Program
{
    static void Main()
    {
        PerformanceCounterCategory pcg = new PerformanceCounterCategory("Network Interface");
        string instance = pcg.GetInstanceNames()[0];
        PerformanceCounter pcsent = new PerformanceCounter("Network Interface", "Bytes Sent/sec", instance);
        PerformanceCounter pcreceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", instance);

        Console.WriteLine("Bytes Sent: {0}", pcsent.NextValue() / 1024);
        Console.WriteLine("Bytes Received: {0}", pcreceived.NextValue() / 1024);
    }
}
Run Code Online (Sandbox Code Playgroud)

来源:http : //dotnet-snippets.com/snippet/show-network-traffic-sent-and-received/580

  • 它是速度,而不是实际字节 (2认同)