Get Network usage information in UWP apps

Elvis Xia 131 Reputation points Microsoft Employee
2019-10-30T07:21:08.457+00:00

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.

Universal Windows Platform (UWP)
{count} vote

Accepted answer
  1. Roy Li - MSFT 33,371 Reputation points Microsoft Vendor
    2019-10-30T08:11:49.01+00:00

    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://learn.microsoft.com/en-us/windows/msix/desktop/desktop-to-uwp-root

    Thanks

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.