我怎样才能得到 "How many Network data(Mobile or WiFi) used when I call API in c# desktop application"

How can I get "How many Network data(Mobile or WiFi) used when I call API in c# desktop application"

我怎样才能得到"How many Network data(Mobile or WiFi) used when I call API in c# desktop application" 我想知道当我调用 API 服务

时如何获得总使用数据

我完成了以下代码:

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);
    lblCarrierCharge.Text = " Bytes Received: " + ni.GetIPv4Statistics().BytesReceived;
}

API呼叫

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(cloudEndpoint);
request.Method = "Get";
long inputLength = request.ContentLength;
long outputLength = 0;
string responseContent = "";

DateTime beginTimestamp = DateTime.Now;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

计算每次调用接收的总字节数。您想要保存 .GetIPv4Statistics().BytesReceived 的当前值,然后在调用之后执行相同的调用并将新值减去前一个值。

int previousNetworkBytesSent = 0;

foreach (NetworkInterface ni in interfaces)
{
    previousNetworkBytesSent += ni.GetIPv4Statistics().BytesReceived;
}

// perform your call here

int newNetworkBytesSent = 0;

foreach (NetworkInterface ni in interfaces)
{
    newNetworkBytesSent += ni.GetIPv4Statistics().BytesReceived;
}

int totalBytesUsed = newNetworkBytesSent - previousNetworkBytesSent;

检查数据类型是否合适,欢迎优化。