Programmatically disconnect network connectivity

前端 未结 2 1854
南方客
南方客 2020-12-17 20:34

Is there a way to programmatically and temporarily disconnect network connectivity in .NET 4.0?

I know I can get the current network connectivity status by doing thi

2条回答
  •  春和景丽
    2020-12-17 21:07

    You could do it with WMI. Here's one we use for disabling the physical adapter to test these types of scenarios.

    using System.Management;
    using System.Linq;
    
    namespace DisableNIC
    {
        internal static class Program
        {
            private static void Main()
            {
                var wmiQuery = new SelectQuery("SELECT * FROM Win32_NetworkAdapter " +
                                                "WHERE NetConnectionId != null " +
                                                  "AND Manufacturer != 'Microsoft' ");
                using (var searcher = new ManagementObjectSearcher(wmiQuery))
                {
                    foreach (var item in searcher.Get().OfType())
                    {
                        if ((string) item["NetConnectionId"] != "Local Area Connection")
                            continue;
    
                        using (item)
                        {
                            item.InvokeMethod("Disable", null);
                        }
                    }
                }
            }
        }
    }
    

    You didn't indicate the OS, but this works in Windows 7 and Windows 8.

    Note that you will need to be an administrator for this to function.

提交回复
热议问题