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

本文关键字:启用 网络 连接 | 更新日期: 2023-09-27 17:47:25

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

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

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

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

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

msdn 上的Win32_NetworkAdapter

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

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

如果您正在寻找一种非常简单的方法,请点击:

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

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

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

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

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

注意:我在WindowsXP中使用它,它在这里可以正常工作。但在windows7中,它无法正常工作。

  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

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

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

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

看看这里的其他答案,虽然有些有效,但有些无效。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;
    }
}