如何在 C# 中禁用/启用网络连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/172875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 16:38:02  来源:igfitidea点击:

How to disable/enable network connection in c#

c#networkinglan

提问by

Basically I'm running some performance tests and don't want the external network to be the drag factor. I'm looking into ways of disabling network LAN. What is an effective way of doing it programmatically? I'm interested in c#. If anyone has a code snippet that can drive the point home that would be cool.

基本上我正在运行一些性能测试并且不希望外部网络成为阻力因素。我正在研究禁用网络 LAN 的方法。以编程方式执行此操作的有效方法是什么?我对 c# 感兴趣。如果有人有一个代码片段可以把重点带回家,那会很酷。

回答by Melvyn

Found this thread while searching for the same thing, so, here is the answer :)

在搜索相同的东西时找到了这个线程,所以,这里是答案:)

The best method I tested in C# uses WMI.

我在 C# 中测试的最佳方法使用 WMI。

http://www.codeproject.com/KB/cs/EverythingInWmi02.aspx

http://www.codeproject.com/KB/cs/EverythingInWmi02.aspx

Win32_NetworkAdapter on msdn

msdn 上的 Win32_NetworkAdapter

C# Snippet : (System.Management must be referenced in the solution, and in using declarations)

C# Snippet :(必须在解决方案和 using 声明中引用 System.Management)

SelectQuery wmiQuery = new SelectQuery("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionId != NULL");
ManagementObjectSearcher searchProcedure = new ManagementObjectSearcher(wmiQuery);
foreach (ManagementObject item in searchProcedure.Get())
{
    if (((string)item["NetConnectionId"]) == "Local Network Connection")
    {
       item.InvokeMethod("Disable", null);
    }
}

回答by Kamrul Hasan

Using netsh Command, you can enable and disable “Local Area Connection”

使用 netsh 命令,您可以启用和禁用“本地连接”

  interfaceName is “Local Area Connection”.

  static void Enable(string interfaceName)
    {
     System.Diagnostics.ProcessStartInfo psi =
            new System.Diagnostics.ProcessStartInfo("netsh", "interface set interface \"" + interfaceName + "\" enable");
        System.Diagnostics.Process p = new System.Diagnostics.Process();
        p.StartInfo = psi;
        p.Start();
    }

    static void Disable(string interfaceName)
    {
        System.Diagnostics.ProcessStartInfo psi =
            new System.Diagnostics.ProcessStartInfo("netsh", "interface set interface \"" + interfaceName + "\" disable");
        System.Diagnostics.Process p = new System.Diagnostics.Process();
        p.StartInfo = psi;
        p.Start();
    }

回答by Kamrul Hasan

In VB.Net , You can also use it for toggle Local Area Connection

在 VB.Net 中,您还可以使用它来切换本地连接

Note: myself use it in Windows XP, it's work here properly. but in windows 7 it's not work properly.

注意:我在 Windows XP 中使用它,它在这里工作正常。但在 Windows 7 中它不能正常工作。

  Private Sub ToggleNetworkConnection()

    Try


        Const ssfCONTROLS = 3


        Dim sConnectionName = "Local Area Connection"

        Dim sEnableVerb = "En&able"
        Dim sDisableVerb = "Disa&ble"

        Dim shellApp = CreateObject("shell.application")
        Dim WshShell = CreateObject("Wscript.Shell")
        Dim oControlPanel = shellApp.Namespace(ssfCONTROLS)

        Dim oNetConnections = Nothing
        For Each folderitem In oControlPanel.items
            If folderitem.name = "Network Connections" Then
                oNetConnections = folderitem.getfolder : Exit For
            End If
        Next


        If oNetConnections Is Nothing Then
            MsgBox("Couldn't find 'Network and Dial-up Connections' folder")
            WshShell.quit()
        End If


        Dim oLanConnection = Nothing
        For Each folderitem In oNetConnections.items
            If LCase(folderitem.name) = LCase(sConnectionName) Then
                oLanConnection = folderitem : Exit For
            End If
        Next


        If oLanConnection Is Nothing Then
            MsgBox("Couldn't find '" & sConnectionName & "' item")
            WshShell.quit()
        End If


        Dim bEnabled = True
        Dim oEnableVerb = Nothing
        Dim oDisableVerb = Nothing
        Dim s = "Verbs: " & vbCrLf
        For Each verb In oLanConnection.verbs
            s = s & vbCrLf & verb.name
            If verb.name = sEnableVerb Then
                oEnableVerb = verb
                bEnabled = False
            End If
            If verb.name = sDisableVerb Then
                oDisableVerb = verb
            End If
        Next



        If bEnabled Then
            oDisableVerb.DoIt()
        Else
            oEnableVerb.DoIt()
        End If


    Catch ex As Exception
        MsgBox(ex.Message)
    End Try

End Sub

回答by micharaze

I modfied the best voted solutionfrom Kamrul Hasanto one methode and added to wait for the exit of the process, cause my Unit Test code run faster than the process disable the connection.

我modfied的最佳解决方案评选卡玛鲁尔·哈桑一个梅索德并添加到等待进程的退出,导致我的单元测试代码的运行比过程更快禁用连接。

private void Enable_LocalAreaConection(bool isEnable = true)
    {
        var interfaceName = "Local Area Connection";
        string control;
        if (isEnable)
            control = "enable";
        else
            control = "disable";
        System.Diagnostics.ProcessStartInfo psi =
               new System.Diagnostics.ProcessStartInfo("netsh", "interface set interface \"" + interfaceName + "\" " + control);
        System.Diagnostics.Process p = new System.Diagnostics.Process();
        p.StartInfo = psi;
        p.Start();
        p.WaitForExit();
    }

回答by Chris Bols

For Windows 10 Change this: for diable ("netsh", "interface set interface name=" + interfaceName + " admin=DISABLE") and for enable ("netsh", "interface set interface name=" + interfaceName + " admin=ENABLE") And use the program as Administrator

对于 Windows 10 更改此项:对于 diable ("netsh", "interface set interface name=" + interfaceName + " admin=DISABLE") 和对于 enable ("netsh", "interface set interface name=" + interfaceName + " admin= ENABLE") 并以管理员身份使用该程序

    static void Disable(string interfaceName)
    {

        //set interface name="Ethernet" admin=DISABLE
        System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("netsh", "interface set interface name=" + interfaceName + " admin=DISABLE");
        System.Diagnostics.Process p = new System.Diagnostics.Process();

        p.StartInfo = psi;
        p.Start();
    }

    static void Enable(string interfaceName)
    {
        System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("netsh", "interface set interface name=" + interfaceName + " admin=ENABLE");
        System.Diagnostics.Process p = new System.Diagnostics.Process();
        p.StartInfo = psi;
        p.Start();
    }

And use the Program as Administrator !!!!!!

并以管理员身份使用程序!!!!!!

回答by Chris Bols

If you are looking for a very simple way to do it, here you go:

如果您正在寻找一种非常简单的方法来做到这一点,请访问:

    System.Diagnostics.Process.Start("ipconfig", "/release"); //For disabling internet
    System.Diagnostics.Process.Start("ipconfig", "/renew"); //For enabling internet

Make sure you run as administrator. I hope you found this helpful!

确保以管理员身份运行。我希望你觉得这有帮助!

回答by FarhadMohseni

best solution is disabling all network adapters regardless of the interface name is disabling and enabling all network adapters using this snippet (Admin rights needed for running , otherwise ITS WONT WORK) :

最好的解决方案是禁用所有网络适配器,而不管接口名称是否使用此代码段禁用和启用所有网络适配器(运行需要管理员权限,否则将无法工作):

  static void runCmdCommad(string cmd)
    {
        System.Diagnostics.Process process = new System.Diagnostics.Process();
        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
        //startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
        startInfo.FileName = "cmd.exe";
        startInfo.Arguments = $"/C {cmd}";
        process.StartInfo = startInfo;
        process.Start();
    }
   static void DisableInternet(bool enable)
    {
        string disableNet = "wmic path win32_networkadapter where PhysicalAdapter=True call disable";
        string enableNet = "wmic path win32_networkadapter where PhysicalAdapter=True call enable";
        runCmdCommad(enable ? enableNet :disableNet);
    }