我想计算在特定时间间隔内下载和上传的总数据,并将其存储到数据库中,以便以后查看。因此,此特定用户此时登录并下载并上传了这么多数据。
我想在C#中执行此操作。
答案 0 :(得分:0)
您可以使用PerformanceCounter
命名空间中的System.Diagnostics
类来完成此操作。
注意两个课程,这将帮助你实现你想做的事情。
NetworkMonitor
上课
public class NetworkMonitor
{
private ArrayList adapters;
public ArrayList monitoredAdapters;
public NetworkMonitor()
{
this.adapters = new ArrayList();
this.monitoredAdapters = new ArrayList();
EnumerateNetworkAdapters();
}
private void EnumerateNetworkAdapters()
{
PerformanceCounterCategory category = new PerformanceCounterCategory("Network Interface");
foreach (string name in category.GetInstanceNames())
{
if (name == "MS TCP Loopback interface")
continue;
NetworkAdapter adapter = new NetworkAdapter(name);
adapter.dlCounter = new PerformanceCounter("Network Interface", "Bytes Received/sec", name);
adapter.ulCounter = new PerformanceCounter("Network Interface", "Bytes Sent/sec", name);
this.adapters.Add(adapter);
adapter.init();
}
}
public NetworkAdapter[] Adapters
{
get
{
return (NetworkAdapter[])this.adapters.ToArray(typeof(NetworkAdapter));
}
}
}
NetworkAdapter
上课
public class NetworkAdapter
{
// Instances of this class are supposed to be created only in an NetworkMonitor.
internal NetworkAdapter(string name)
{
this.name = name;
}
private long dlSpeed, ulSpeed;
private long dlValue, ulValue;
private long dlValueOld, ulValueOld;
internal string name;
internal PerformanceCounter dlCounter, ulCounter;
internal bool Enabled;
internal void init()
{
this.dlValueOld = this.dlCounter.NextSample().RawValue;
this.ulValueOld = this.ulCounter.NextSample().RawValue;
this.Enabled = true;
}
// Obtain new sample from performance counters, and refresh the values saved in dlSpeed, ulSpeed, etc.
// This method is supposed to be called only in NetworkMonitor, one time every second.
internal void refresh()
{
this.dlValue = this.dlCounter.NextSample().RawValue;
this.ulValue = this.ulCounter.NextSample().RawValue;
// Calculates download and upload speed.
this.dlSpeed = this.dlValue - this.dlValueOld;
this.ulSpeed = this.ulValue - this.ulValueOld;
this.dlValueOld = this.dlValue;
this.ulValueOld = this.ulValue;
}
// Overrides method to return the name of the adapter.
public override string ToString()
{
return this.name;
}
public string Name
{
get
{
return this.name;
}
}
// Current download speed in bytes per second.
public long DownloadSpeed(int Interval)
{
return this.dlSpeed * 1000 / Interval;
}
// Current upload speed in bytes per second.
public long UploadSpeed(int Interval)
{
return this.ulSpeed * 1000 / Interval;
}
}
您所要做的就是:
long downloadSpeed = 0;
long uploadSpeed = 0;
NetworkMonitor networkMonitor = new NetworkMonitor();
foreach (NetworkAdapter adapter in monitor.Adapters)
{
if (adapter.Enabled)
{
adapter.refresh();
downloadSpeed += adapter.DownloadSpeed(yourTimerInterval);
uploadSpeed += adapter.UploadSpeed(yourTimerInterval);
}
}
希望这会有所帮助。 问候。