【问题标题】:How to disable/enable network connection in c#如何在 C# 中禁用/启用网络连接
【发布时间】:2010-09-15 10:21:10
【问题描述】:

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

【问题讨论】:

  • Something similar 已讨论。
  • 是的,但这有实际工作的 C# 代码。
  • 好问题似乎具有长期相关性。支持价值问题。很多好的答案,最好不要将单个答案确定为答案。有时越简单越好,如果您只想切换网络,桌面上的 .bat 文件中的 netsh 可能会解决问题。但是我来这里也是为了寻找代码示例来检测和切换连接,所以这里的代码很棒——即使是 6 年后。

标签: c# networking lan


【解决方案1】:

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

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

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

Win32_NetworkAdapter on msdn

C# 代码段:(必须在解决方案和使用声明中引用 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);
    }
}

【讨论】:

  • 请注意,我必须以管理员身份运行它(当我以 peon 身份运行时,InvokeMethod() 没有返回错误)。
  • 这看起来不错,但不适用于通用 Windows 应用程序。
  • 刚刚在 Windows Build 20H2 上的 .NET 项目中使用了代码。以管理员身份运行,它会关闭适配器。我还使用成员 NetConnectionId 来检查“WLAN”和“以太网”的出现,以不关闭蓝牙适配器。 Win32_NetworkAdapter 的一个很好的解释可以在这里找到:docs.microsoft.com/en-us/windows/win32/cimwin32prov/…
【解决方案2】:

使用 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();
    }

【讨论】:

  • 在使用 WMI 数小时后(显然不是每个适配器都提供 Disable 命令或类似命令),netsh 在第一次尝试时运行顺利。
  • 请记住,这也必须以管理员身份运行
  • 对我来说效果很好!我虽然会很难,但你为我做的。 Tnx。
  • 工作正常。更喜欢这种方法方法 /release 因为我不想更改 IP 地址。 X
【解决方案3】:

如果您正在寻找一种非常简单的方法来做到这一点,那就去吧:

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

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

【讨论】:

  • 即使不是管理员也可以为我工作
【解决方案4】:

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

注意:我自己在 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

【讨论】:

    【解决方案5】:

    对于 Windows 10 更改此: 为禁用 ("netsh", "interface set interface name=" + interfaceName + " admin=DISABLE") 并启用 ("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();
        }
    

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

    【讨论】:

      【解决方案6】:

      最好的解决方案是禁用所有网络适配器,无论接口名称如何,都使用此 sn-p 禁用和启用所有网络适配器(运行需要管理员权限,否则它无法工作):

        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);
          }
      

      【讨论】:

        【解决方案7】:

        我将best voted solutionKamrul Hasan 修改为一种方法并添加以等待进程退出,导致我的单元测试代码运行速度快于进程禁用连接。

        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();
            }
        

        【讨论】:

          【解决方案8】:

          在这里查看其他答案,虽然有些有效,但有些无效。 Windows 10 使用与此链中较早使用的不同的 netsh 命令。其他解决方案的问题在于,它们将打开一个用户可见的窗口(尽管只有几分之一秒)。下面的代码将静默启用/禁用网络连接。

          下面的代码肯定可以清理,但这是一个好的开始。

          ***请注意必须以管理员身份运行才能工作***

          //Disable network interface
          static public void Disable(string interfaceName)
          {
              System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
              startInfo.FileName = "netsh";
              startInfo.Arguments = $"interface set interface \"{interfaceName}\" disable";
              startInfo.RedirectStandardOutput = true;
              startInfo.RedirectStandardError = true;
              startInfo.UseShellExecute = false;
              startInfo.CreateNoWindow = true;
              System.Diagnostics.Process processTemp = new System.Diagnostics.Process();
              processTemp.StartInfo = startInfo;
              processTemp.EnableRaisingEvents = true;
              try
              {
                  processTemp.Start();
              }
              catch (Exception e)
              {
                  throw;
              }
          }
          
          //Enable network interface
          static public void Enable(string interfaceName)
          {
              System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
              startInfo.FileName = "netsh";
              startInfo.Arguments = $"interface set interface \"{interfaceName}\" enable";
              startInfo.RedirectStandardOutput = true;
              startInfo.RedirectStandardError = true;
              startInfo.UseShellExecute = false;
              startInfo.CreateNoWindow = true;
              System.Diagnostics.Process processTemp = new System.Diagnostics.Process();
              processTemp.StartInfo = startInfo;
              processTemp.EnableRaisingEvents = true;
              try
              {
                  processTemp.Start();
              }
              catch (Exception e)
              {
                  throw;
              }
          }
          

          【讨论】:

            猜你喜欢
            • 2016-05-07
            • 1970-01-01
            • 2013-11-18
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多