question

elvisxia avatar image
1 Vote"
elvisxia asked ·

Get Network usage information in UWP apps

We have a WPF app which is used for monitor Network for the desktop. Now my team decides to create a new UWP app to implement the similar functions. Currently I am trying to show network usage info in UWP, but I don’t know where to start and what API should I use? Any idea will be apricated.

windows-uwp
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

RoyLi-MSFT avatar image
1 Vote"
RoyLi-MSFT answered ·

Hello,

Welcome to our Microsoft Q&A platform!

In order to get the Network usage of your device, you will need to get the ConnectionProfile of your device first.
Then you could call ConnectionProfile.GetNetworkUsageAsync() method to get the Network usage in a period of time.
Here is a sample about this:

 private async void Button_Click(object sender, RoutedEventArgs e)
         {
    
             ConnectionProfile internetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();
             var currentDate = DateTime.Now.AddDays(-4);
             var startDate = DateTime.Now.AddDays(-5);
    
             NetworkUsageStates NetworkUsageStates = new NetworkUsageStates();
             NetworkUsageStates.Roaming = TriStates.No;
             NetworkUsageStates.Shared = TriStates.No;
    
             // dierctly using  NetworkUsageStates object without setting roaming and shared property will get null result.
             //var networkUsage = await internetConnectionProfile.GetNetworkUsageAsync(utcTimeA, utcTimeB, DataUsageGranularity.Total, new NetworkUsageStates()) ;
             var networkUsage = await internetConnectionProfile.GetNetworkUsageAsync(startDate, currentDate, DataUsageGranularity.Total, NetworkUsageStates);
             foreach ( var usage in networkUsage) 
             {
                 var received = usage.BytesReceived;
                 var sent = usage.BytesSent;
             }
         }

Besides, another way to implement a similar function in your UWP app as what your WPF app does is to simply convert your WPF app to the UWP app by using Desktop Bridge, in this way you do not need to rewrite all the code and you can leavage UWP APIs to add modern experiences to your app on Windows 10.
For more information please check:

Desktop Bridge docs:
https://docs.microsoft.com/en-us/windows/msix/desktop/desktop-to-uwp-root

Thanks



· Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.