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.