UWP get data usage

你说的曾经没有我的故事 提交于 2020-01-07 05:44:09

问题


I love programming for UWP and I start new program with C# and UWP. I want to get network usage for each connection in the target system. I read document in MSDN and I write this code for my app:

public async static Task<List<ConnectionReport>> GetNetworkUsageAsync(string ConnectionName, DateTimeOffset StartTime, DateTimeOffset EndTime, DataUsageGranularity Granularity)
{
    var granularityTimeSpan = GranularityToTimeSpan(Granularity);
    try
    {
        var connectionProfile = GetConnectionProfile(ConnectionName);
        var networkUsages = await connectionProfile.GetNetworkUsageAsync(StartTime, EndTime, Granularity, new NetworkUsageStates());
        List<ConnectionReport> listNetworkUsage = new List<ConnectionReport>();
        foreach (var networkUsage in networkUsages)
        {
            var connectionReport = new ConnectionReport()
            {
                Date = StartTime.Date.ToString(dateFormat),
                Download = ConvertBytesToMB(networkUsage.BytesReceived),
                Upload = ConvertBytesToMB(networkUsage.BytesSent),
            };                                     
            listNetworkUsage.Add(connectionReport);
            StartTime = StartTime.Add(granularityTimeSpan);
        }
        return listNetworkUsage;
    }
    catch (Exception ex)
    {                
        // do something
    } 
}         

private static ConnectionProfile GetConnectionProfile(string ConnectionName)
{
    var connectionProfiles = NetworkInformation.GetConnectionProfiles();
    foreach (var connection in connectionProfiles)
    {
        if (connection.ProfileName == ConnectionName)
            return connection;
    }            
}

private static double ConvertBytesToMB(double bytes) => Math.Round(bytes / 1024 / 1024, 3); 

// Returns the amount of time between each period of network usage for a given granularity
private static TimeSpan GranularityToTimeSpan(DataUsageGranularity granularity)
{
    switch (granularity)
    {
        case DataUsageGranularity.PerMinute:
            return new TimeSpan(0, 1, 0);
        case DataUsageGranularity.PerHour:
            return new TimeSpan(1, 0, 0);
        case DataUsageGranularity.PerDay:
            return new TimeSpan(1, 0, 0, 0);
        default:
            return new TimeSpan(0);
    }
} 

But I don't know my code have some problems or windows 10 build 15063 have some problems because I run my app on two different system and I get same value for all WiFi and Ethernet connections. I always get my network usage with this code but not for a special connection, It's give me my Internet usage however I choose 2 different WiFi.
Is it possible to say me that it is windows problem or my code have some problems?
Thanks.

来源:https://stackoverflow.com/questions/45781041/uwp-get-data-usage

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!