C# How to get network adapter status properties like Duration and How to filter Virtual network from list of networks.

How to check network connection duration?

Please follow below steps to check network duration.

Open "Control Panel" -> click on "Network and Internet" -> click "Network and Sharing Center" -> Click on Network Property. Now you can see as per below.

Network Duration

To find duration in C# you can refer below code snippet.
Add reference from Network List Manager 1.0 Type Library (NETWORKLIST) dll from windows. 

var manager = new NetworkListManager();
var connectedNetworks = manager.GetNetworks(NLM_ENUM_NETWORK.NLM_ENUM_NETWORK_CONNECTED) .Cast<INetwork>();
foreach (var network in connectedNetworks) 
        if (network.IsConnected)  
              network.GetTimeCreatedAndConnected(out uint _, out uint _, out uint 
                  pdwLowDateTimeConnected, out uint pdwHighDateTimeConnected);
DateTime networkConnectedTime = DateTime.FromFileTimeUtc((long) 
                (((ulong)pdwHighDateTimeConnected << 32) | pdwLowDateTimeConnected));
                TimeSpan diff = DateTime.Now.Subtract(networkConnectedTime);
        Console.WriteLine("Name: " + network.GetName() + "  Duration : {0} day(s) {1}:{2}:  {3}", diff.Days, diff.Hours, diff.Minutes, diff.Seconds);

How to detect Virtual network: 

    To filter out virtual networks from list of networks available at windows. Possible network connections are available at windows like Wireless, LAN, VPN etc. Refer below code snippet to filter out the virtual networks. Virtual networks means VPN and other networks which does not contains physical adapter.

IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
List<IPAddress> localAddr = host.AddressList.Where(ip=>ip.AddressFamily == AddressFamily.InterNetwork).ToList();
var networks = NetworkInterface.GetAllNetworkInterfaces().Where(net=>IsPhysicalAdapter(net));

Private Static bool IsPhysicalAdapter (NetworrkInterface ni)
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"root/CIMV2", 
string.Format("SELECT * FROM Win32_NetworkAdapter WHERE GUID='{0}'",ni.Id));
ManagementObjectCollection collection=searcher.Get();
return collection?.Count>0;
Next Post »