The following code example shows how to use the SetNetworkPreference extension method. In this example, the preferred network interface is Cellular. If a cellular network interface is not available, another network interface is used. GetCurrentNetworkInterface is called in the request callback to determine what network interface was used.

privatevoid StartDownload()
{
HttpWebRequest request;
// A NetworkException with the error NetworkError.WebRequestAlreadyFinished will// be thrown if GetCurrentNetworkInterface is called after the request is complete.// The uri string used here is for illustration purposes only. It may complete before// you call GetCurrentNetworkInterface. Replace this with a longer-running request if needed.
request = (HttpWebRequest)WebRequest.Create("http://www.contoso.com/example.aspx");
request.AllowReadStreamBuffering = false;
// Our preference, for this example, is a cellular network interface. // Call SetNetworkPreference on an HttpWebRequest before calling BeginGetResponse or// an InvalidOperationException will be thrown.
request.SetNetworkPreference(NetworkSelectionCharacteristics.Cellular);
IAsyncResult result = (IAsyncResult)request.BeginGetResponse(new AsyncCallback(response_Callback), request);
}
privatevoid response_Callback(IAsyncResult asyncResult)
{
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
// Check to see what network interface is being used. // The call to GetCurrentNetworkInterface must be invoked on the UI thread.
Dispatcher.BeginInvoke(() =>
{
try
{
NetworkInterfaceInfo ni = request.GetCurrentNetworkInterface();
// If a cellular interface was available, we should see that here, since that was our// preference. Otherwise, we will get a different network interface type, such as Ethernet
System.Diagnostics.Debug.WriteLine(ni.InterfaceType.ToString());
}
catch (NetworkException networkException)
{
// If the HttpWebRequest was not long running, then this exception will be thrown for// the GetCurrentNetworkInterface above.if (networkException.NetworkErrorCode == NetworkError.WebRequestAlreadyFinished)
{
System.Diagnostics.Debug.WriteLine("Cannot call GetCurrentNetworkInterface if the web request is already complete");
}
}
});
}