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

时间:2008-10-05 23:59:32

标签: c# networking lan

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

8 个答案:

答案 0 :(得分:27)

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

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

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

Win32_NetworkAdapter on msdn

C#Snippet :(必须在解决方案中引用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);
    }
}

答案 1 :(得分:15)

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

答案 2 :(得分: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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

对于Windows 10更改此: 为了diable (“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();
    }

使用程序管理员!!!!!!

答案 5 :(得分:0)

如果您正在寻找一种非常简单的方法,请按以下步骤操作:

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

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

答案 6 :(得分:0)

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

  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 :(得分: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;
    }
}