UWP获取数据使用

时间:2017-08-20 10:18:55

标签: c# uwp

我喜欢为UWP编程,我用C#和UWP开始新程序。我想获得目标系统中每个连接的网络使用情况。我在MSDN中阅读了文档,并为我的应用程序编写了此代码:

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);
    }
} 

但是我不知道我的代码有一些问题或者windows 10 build 15063有一些问题因为我在两个不同的系统上运行我的应用程序而且我获得了所有WiFi和以太网连接的相同值。我总是通过这个代码获得我的网络使用,但不是为了一个特殊的连接,它给我我的互联网使用,但我选择2个不同的WiFi。
有可能说我是windows问题或我的代码有问题吗? 感谢。

0 个答案:

没有答案