using System.Net.NetworkInformation; using System.Timers; namespace Monitor { public class MonitorNetwork { public string UpSpeed { get; set; } public string DownSpeed { get; set; } public string AllTraffic { get; set; } private string NetCardDescription { get; set; } //建立连接时上传的数据量 private long BaseTraffic { get; set; } private long OldUp { get; set; } private long OldDown { get; set; } private NetworkInterface networkInterface { get; set; } private Timer timer = new Timer() { Interval = 1000 }; public void Close() { timer.Stop(); } public MonitorNetwork(string netCardDescription) { timer.Elapsed += Timer_Elapsed; NetCardDescription = netCardDescription; timer.Interval = 1000; } public bool Start() { networkInterface = null; NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (var var in nics) { if (var.Description.Contains(NetCardDescription)) { networkInterface = var; break; } } if (networkInterface == null) { return false; } else { BaseTraffic = (networkInterface.GetIPStatistics().BytesSent + networkInterface.GetIPStatistics().BytesReceived); OldUp = networkInterface.GetIPStatistics().BytesSent; OldDown = networkInterface.GetIPStatistics().BytesReceived; timer.Start(); return true; } } private string[] units = new string[] {"KB/s","MB/s","GB/s" }; private void CalcUpSpeed() { long nowValue = networkInterface.GetIPStatistics().BytesSent; int num = 0; double value = (nowValue - OldUp) / 1024.0; while (value > 1023) { value = (value / 1024.0); num++; } UpSpeed = value.ToString("0.0") + units[num]; OldUp = nowValue; } private void CalcDownSpeed() { long nowValue = networkInterface.GetIPStatistics().BytesReceived; int num = 0; double value = (nowValue - OldDown) / 1024.0; while (value > 1023) { value = (value / 1024.0); num++; } DownSpeed = value.ToString("0.0") + units[num]; OldDown = nowValue; } private string[] unitAlls = new string[] { "KB", "MB", "GB" ,"TB"}; private void CalcAllTraffic() { long nowValue = OldDown+OldUp; int num = 0; double value = (nowValue- BaseTraffic) / 1024.0; while (value > 1023) { value = (value / 1024.0); num++; } AllTraffic = value.ToString("0.0") + unitAlls[num]; } private void Timer_Elapsed(object sender, ElapsedEventArgs e) { CalcUpSpeed(); CalcDownSpeed(); CalcAllTraffic(); } } }
Austin Liu 刘恒辉
Project Manager and Software Designer E-Mail:lzhdim@163.com Blog:https://lzhdim.cnblogs.com 欢迎收藏和转载此博客中的博文,但是请注明出处,给笔者一个与大家交流的空间。谢谢大家。 |