Freigeben über


How to retrieve network connection information (XAML)

This topic shows how to retrieve connectivity details and usage information for network connections on a device using classes in the Windows.Networking.Connectivity namespace.

Prerequisites

The following examples use C# or C++ and are based on the Network information sample. For general help creating a Windows Runtime app using C# or Visual Basic, see Create your first Windows Runtime app using C# or Visual Basic. For general help creating a Windows Runtime app using C++, see Create your first Windows Runtime app using C++.

What is a connection profile?

A ConnectionProfile represents a single network connection established on a device. The information accessed from a ConnectionProfile can be used to determine the current connectivity level, track data usage, or identify the network adapter used to maintain the connection. By registering to be notified of changes to the properties of a ConnectionProfile, your connected Windows Runtime app can make the right choices when adapting its behavior for changes in a network environment. For more information see, How to manage network connection events and changes in availability.

For more specialized scenarios, like connected applications for mobile devices that frequently roam and operate on metered networks, a ConnectionProfile provides cost and data plan information that can be used to prevent unexpected carrier service fees. For more information, see How to manage metered network cost constraints.

Each ConnectionProfile provides access to the following connection information:

Data Supplied By Description

Connection Cost

ConnectionCost

Cost details, including data limit and roaming information.

Cost Type

NetworkCostType

Cost type of the network currently used by the connection.

Data Plan Status & Usage

DataPlanStatus, DataPlanUsage

Usage information specific to the data plan associated with the connection.

Local Usage

NetworkUsage

Local connection usage information.

Network Adapter

NetworkAdapter

Network adapter that provides connectivity for the connection.

WLAN and WWAN connection properties

WlanConnectionProfileDetails

WwanConnectionProfileDetails

Provides additional details that are specific to WLAN and WWAN connection profiles.

 

Retrieving connection profiles

The NetworkInformation class is a static class that defines the methods your app uses to retrieve a ConnectionProfile. The NetworkInformation class defines two methods for retrieving a ConnectionProfile. If you only need to return the profile associated with the Internet connection, use the GetInternetConnectionProfile method.

You must write code to handle exceptions when you call most asynchronous network methods. Also the methods in the Windows.Networking.Connectivity namespace that retrieve a ConnectionProfile can throw exceptions. Your exception handler can retrieve more detailed information on the cause of the exception to better understand the failure and make appropriate decisions. For more information, see How to handle exceptions in network apps.

    //Get the Internet connection profile
    string connectionProfileInfo = string.Empty;
    try {
        ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();

        if (InternetConnectionProfile == null) {
            NotifyUser("Not connected to Internet\n");
        }
        else {
            connectionProfileInfo = GetConnectionProfile(InternetConnectionProfile);
            NotifyUser("Internet connection profile = " +connectionProfileInfo);
        }
    }
    catch (Exception ex) {
        NotifyUser("Unexpected exception occurred: " + ex.ToString());
    }

If you want to retrieve profiles for all connections (including the Internet connection), use the GetConnectionProfiles method.

    // Get all connection profiles
    string connectionProfileList = string.Empty;
    try {
        var ConnectionProfiles = NetworkInformation.GetConnectionProfiles();
        foreach (var connectionProfile in ConnectionProfiles) {
            //Display Profile information for each of the connection profiles
            connectionProfileList += GetConnectionProfile(connectionProfile);
            connectionProfileList += "--------------------------------------------------------------------\n";
        }
            NotifyUser("Internet connection profile = " +connectionProfileList);
    }
    catch (Exception ex) {
        NotifyUser("Unexpected exception occurred: " + ex.ToString());
    }

Accessing information from a connection profile

The following example code calls methods on the ConnectionProfile to retrieve network connection state, connection cost and data plan status information. The GetConnectionCost method on the ConnectionProfile retrieves the ConnectionCost information for the profile. The GetDataPlanStatus method on the ConnectionProfile retrieves the DataPlanStatus information for the profile. Other methods on the ConnectionProfile can retrieve information on wirelsss LAN information when the connection profile uses Wi-Fi or wireless WAN information when the connection profile uses mobile broadband.

//Get some ConnectionProfile information
//
string GetConnectionProfile(ConnectionProfile connectionProfile)
{
    string connectionProfileInfo = string.Empty;
    if (connectionProfile != null) {
        connectionProfileInfo = "Profile Name : " + connectionProfile.ProfileName + "\n";

        switch (connectionProfile.GetNetworkConnectivityLevel()) {
            case NetworkConnectivityLevel.None:
                connectionProfileInfo += "Connectivity Level : None\n";
                break;
            case NetworkConnectivityLevel.LocalAccess:
                connectionProfileInfo += "Connectivity Level : Local Access\n";
                break;
            case NetworkConnectivityLevel.ConstrainedInternetAccess:
                connectionProfileInfo += "Connectivity Level : Constrained Internet Access\n";
                break;
            case NetworkConnectivityLevel.InternetAccess:
                connectionProfileInfo += "Connectivity Level : Internet Access\n";
                break;
        }

        switch (connectionProfile.GetDomainConnectivityLevel()) {
            case DomainConnectivityLevel.None:
                connectionProfileInfo += "Domain Connectivity Level : None\n";
                break;
            case DomainConnectivityLevel.Unauthenticated:
                connectionProfileInfo += "Domain Connectivity Level : Unauthenticated\n";
                break;
            case DomainConnectivityLevel.Authenticated:
                connectionProfileInfo += "Domain Connectivity Level : Authenticated\n";
                break;
        }

        //Get Connection Cost information
        ConnectionCost connectionCost = connectionProfile.GetConnectionCost();
        connectionProfileInfo += GetConnectionCostInfo(connectionCost);

        //Get Dataplan Status information
        DataPlanStatus dataPlanStatus = connectionProfile.GetDataPlanStatus();
        connectionProfileInfo += GetDataPlanStatusInfo(dataPlanStatus);
                
    }
    return connectionProfileInfo;
}

// Get ConnectionCost information for a profile
string GetConnectionCostInfo(ConnectionCost connectionCost)
{
    string cost = string.Empty;
    cost += "Connection Cost Information: \n";
    cost += "====================\n";

    if (connectionCost == null) {
        cost += "Connection Cost not available\n";
        return cost;
    }

    switch (connectionCost.NetworkCostType) {
         case NetworkCostType.Unrestricted:
             cost += "Cost: Unrestricted";
             break;
         case NetworkCostType.Fixed:
             cost += "Cost: Fixed";
             break;
         case NetworkCostType.Variable:
             cost += "Cost: Variable";
             break;
         case NetworkCostType.Unknown:
             cost += "Cost: Unknown";
             break;
         default:
             cost += "Cost: Error";
             break;
     }
     cost += "\n";
     cost += "Roaming: " + connectionCost.Roaming + "\n";
     cost += "Over Data Limit: " + connectionCost.OverDataLimit + "\n";
     cost += "Approaching Data Limit : " + connectionCost.ApproachingDataLimit + "\n";

     return cost;
}

// Get DataPlanStatus information for a profile
string GetDataPlanStatusInfo(DataPlanStatus dataPlan)
{
    string dataplanStatusInfo = string.Empty;
    dataplanStatusInfo = "Dataplan Status Information:\n";
    dataplanStatusInfo += "====================\n";

    if (dataPlan == null) {
        dataplanStatusInfo += "Dataplan Status not available\n";
        return dataplanStatusInfo;
    }
            
    if (dataPlan.DataPlanUsage != null) {
        dataplanStatusInfo += "Usage In Megabytes : " + dataPlan.DataPlanUsage.MegabytesUsed + "\n";
        dataplanStatusInfo += "Last Sync Time : " + dataPlan.DataPlanUsage.LastSyncTime + "\n";
    }
    else {
        dataplanStatusInfo += "Usage In Megabytes : Not Defined\n";
    }

    ulong? inboundBandwidth = dataPlan.InboundBitsPerSecond;
    if (inboundBandwidth.HasValue) {
        dataplanStatusInfo += "InboundBitsPerSecond : " + inboundBandwidth + "\n";
    }
    else {
        dataplanStatusInfo += "InboundBitsPerSecond : Not Defined\n";
    }

    ulong? outboundBandwidth = dataPlan.OutboundBitsPerSecond;
    if (outboundBandwidth.HasValue) {
        dataplanStatusInfo += "OutboundBitsPerSecond : " + outboundBandwidth + "\n";
    }
    else {
        dataplanStatusInfo += "OutboundBitsPerSecond : Not Defined\n";
    }

    uint? dataLimit = dataPlan.DataLimitInMegabytes;
    if (dataLimit.HasValue) {
        dataplanStatusInfo += "DataLimitInMegabytes : " + dataLimit + "\n";
    }
    else {
        dataplanStatusInfo += "DataLimitInMegabytes : Not Defined\n";
    }

    System.DateTimeOffset? nextBillingCycle = dataPlan.NextBillingCycle;
    if (nextBillingCycle.HasValue) {
        dataplanStatusInfo += "NextBillingCycle : " + nextBillingCycle + "\n";
    }
    else {
        dataplanStatusInfo += "NextBillingCycle : Not Defined\n";
    }

    uint? maxTransferSize = dataPlan.MaxTransferSizeInMegabytes;
    if (maxTransferSize.HasValue) {
        dataplanStatusInfo += "MaxTransferSizeInMegabytes : " + maxTransferSize + "\n";
    }
    else {
        dataplanStatusInfo += "MaxTransferSizeInMegabytes : Not Defined\n";
    }
    return dataplanStatusInfo;
}

Summary

In this topic we reviewed how to retrieve connection profiles and the connectivity information that each profile contains. Using this information to help your app make the right choices is essential for a reliable connected experience.

For additional guidelines and best practices for using connection information to guide the behavior of your networked app, see How to manage network connection events and changes in availability.

Other

Create your first Windows Runtime app using C# or Visual Basic

Create your first Windows Runtime app using C++

How to handle exceptions in network apps

How to manage metered network cost constraints

How to manage network connection events and changes in availability

How to retrieve network adapter and locality information

How to retrieve network connection usage data

Reference

ConnectionCost

ConnectionProfile

DataPlanStatus

NetworkInformation

Windows.Networking.Connectivity

Samples

Network information sample

Network status background sample