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

30

基本上,我正在运行一些性能测试,不希望外部网络成为制约因素。我正在研究以编程方式禁用网络LAN的方法。如果有任何人有一个能够让人明白的c#代码片段,那就太棒了。


有类似的讨论过。 - hayalci
是的,但这里有实际可用的C#代码。 - Colin
请点击以下链接,它可能会对您有所帮助。https://dev59.com/mHA75IYBdhLWcg3w4tR7 - Buddhika Samith
好问题似乎具有长期的相关性。为了价值,点赞这个问题。有很多好答案,最好不要将其中一个标识为“答案”。有时候简单就是更好的选择,如果你只想切换网络,可以在桌面上使用.bat文件中的netsh命令。但我来到这里也是为了寻找检测和切换连接的代码示例,所以即使是6年后,这里的代码仍然很棒。 - TonyG
8个回答

36

在搜索相同问题时发现了这个帖子,所以,这里是答案 :)

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

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

msdn上的Win32_NetworkAdapter

C#片段:(在解决方案中必须引用System.Management,并在using声明中使用)

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

8
请注意,我必须以管理员身份运行此操作(当我以普通用户身份运行时,InvokeMethod()未返回错误)。 - Colin
这看起来很不错,但它不能用于通用 Windows 应用程序。 - Adam
刚在 Windows Build 20H2 的 .NET 项目中使用了这段代码。以管理员身份运行,它会关闭适配器。我还使用了成员 NetConnectionId 来检查是否出现了“WLAN”和“Ethernet”,以避免关闭蓝牙适配器。关于 Win32_NetworkAdapter 的良好解释可以在此处找到:https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-networkadapter - Nonlinearsound

20

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

1
在经历了几个小时的 WMI 折磨后(显然并不是每个适配器都提供“禁用”命令,或者类似的东西),netsh 在第一次尝试时就顺利地工作了。 - heltonbiker
1
请记住,这也必须以管理员身份运行。 - Patartics Milán
它对我很有效!我以为会很难,但你让它变得容易了。谢谢。 - Mostafa Fahimi
工作得很好。我更喜欢这种方法,而不是使用/release,因为我不想改变IP地址。X - TinyRacoon

5
如果你想寻找一种非常简单的方法来完成它,这里就有了:
    System.Diagnostics.Process.Start("ipconfig", "/release"); //For disabling internet
    System.Diagnostics.Process.Start("ipconfig", "/renew"); //For enabling internet

请确保以管理员身份运行。希望对您有所帮助!


即使不以管理员身份运行,对我来说也有效。 - svstnv

2

如果要在 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();
    }

并且需要以管理员身份运行程序!!!!!!


1
在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

1

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

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

0

我修改了最佳投票解决方案,来自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();
    }

0

看到其他答案,虽然有些有效,但有些不行。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;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接