Подтвердить что ты не робот

Как отключить/включить сетевое подключение в С#

В основном я выполняю некоторые тесты производительности и не хочу, чтобы внешняя сеть была фактором перетаскивания. Я изучаю способы отключения локальной сети. Каков эффективный способ сделать это программно? Меня интересует С#. Если у кого-то есть фрагмент кода, который может управлять точкой, где было бы круто.

4b9b3361

Ответ 1

Нашел этот поток, ища то же самое, так вот вот ответ:)

Лучший метод, который я тестировал на С#, использует WMI.

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

Win32_NetworkAdapter на msdn

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

Ответ 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();
    }

Ответ 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

            namespace CSWMIEnableDisableNetworkAdapter
            {
                partial class MainForm
                {
                    /// <summary>
                    /// Required designer variable.
                    /// </summary>
                    private System.ComponentModel.IContainer components = null;

                    /// <summary>
                    /// Clean up any resources being used.
                    /// </summary>
                    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
                    protected override void Dispose(bool disposing)
                    {
                        if (disposing && (components != null))
                        {
                            components.Dispose();
                        }
                        base.Dispose(disposing);
                    }

                    #region Windows Form Designer generated code

                    /// <summary>
                    /// Required method for Designer support - do not modify
                    /// the contents of this method with the code editor.
                    /// </summary>
                    private void InitializeComponent()
                    {
                        System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
                        this.grpNetworkAdapters = new System.Windows.Forms.GroupBox();
                        this.stsMessage = new System.Windows.Forms.StatusStrip();
                        this.tsslbResult = new System.Windows.Forms.ToolStripStatusLabel();
                        this.stsMessage.SuspendLayout();
                        this.SuspendLayout();
                        // 
                        // grpNetworkAdapters
                        // 
                        this.grpNetworkAdapters.BackColor = System.Drawing.SystemColors.ControlLightLight;
                        resources.ApplyResources(this.grpNetworkAdapters, "grpNetworkAdapters");
                        this.grpNetworkAdapters.Name = "grpNetworkAdapters";
                        this.grpNetworkAdapters.TabStop = false;
                        // 
                        // stsMessage
                        // 
                        this.stsMessage.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
                        this.tsslbResult});
                        resources.ApplyResources(this.stsMessage, "stsMessage");
                        this.stsMessage.Name = "stsMessage";
                        // 
                        // tsslbResult
                        // 
                        this.tsslbResult.BackColor = System.Drawing.SystemColors.Control;
                        this.tsslbResult.Name = "tsslbResult";
                        resources.ApplyResources(this.tsslbResult, "tsslbResult");
                        // 
                        // EnableDisableNetworkAdapterForm
                        // 
                        resources.ApplyResources(this, "$this");
                        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
                        this.BackColor = System.Drawing.SystemColors.ControlLightLight;
                        this.Controls.Add(this.stsMessage);
                        this.Controls.Add(this.grpNetworkAdapters);
                        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
                        this.MaximizeBox = false;
                        this.Name = "EnableDisableNetworkAdapterForm";
                        this.stsMessage.ResumeLayout(false);
                        this.stsMessage.PerformLayout();
                        this.ResumeLayout(false);
                        this.PerformLayout();

                    }

                    #endregion

                    private System.Windows.Forms.GroupBox grpNetworkAdapters;
                    private System.Windows.Forms.StatusStrip stsMessage;
                    private System.Windows.Forms.ToolStripStatusLabel tsslbResult;
                }
            }

Ответ 6

            /****************************** Module Header ******************************\
            * Module Name:  MainForm.cs
            * Project:      CSWMIEnableDisableNetworkAdapter
            * Copyright (c) Microsoft Corporation.
            * 
            * This is the main form of this application. It is used to initialize the UI  
            * and handle the events. 
            * 
            * This source is subject to the Microsoft Public License.

            * All other rights reserved.
            * 
            * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
            * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED 
            * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
            \***************************************************************************/

            using System;
            using System.Threading;
            using System.Collections.Generic;
            using System.Drawing;
            using System.Windows.Forms;
            using System.Security.Principal;
            using CSWMIEnableDisableNetworkAdapter.Properties;


            namespace CSWMIEnableDisableNetworkAdapter
            {
                public partial class MainForm : Form
                {

                    #region Private Properties

                    /// <summary>
                    /// All Network Adapters in the machine
                    /// </summary>
                    private List<NetworkAdapter> _allNetworkAdapters = new List<NetworkAdapter>();

                    /// <summary>
                    /// A ProgressInfo form
                    /// </summary>
                    private ProgressInfoForm _progressInfoForm = new ProgressInfoForm();

                    /// <summary>
                    /// The Current Operation Network Adapter
                    /// </summary>
                    private NetworkAdapter _currentNetworkAdapter = null;

                    #endregion

                    #region Construct EnableDisableNetworkAdapter

                    /// <summary>
                    /// Construct an EnableDisableNetworkAdapter
                    /// </summary>
                    public MainForm()
                    {
                        if (isAdministrator())
                        {
                            InitializeComponent();
                            ShowAllNetworkAdapters();
                            tsslbResult.Text = string.Format("{0}[{1}]", 
                                Resources.StatusTextInitial, 
                                _allNetworkAdapters.Count);
                        }
                        else
                        {
                            MessageBox.Show(Resources.MsgElevatedRequire, 
                                Resources.OneCodeCaption, 
                                MessageBoxButtons.OK, 
                                MessageBoxIcon.Warning);
                            Environment.Exit(1);
                        }
                    }

                    #endregion

                    #region Private Methods

                    /// <summary>
                    /// You need to run this sample as Administrator
                    /// Check whether the application is run as administrator
                    /// </summary>
                    /// <returns>Whether the application is run as administrator</returns>      
                    private bool isAdministrator()
                    {
                        WindowsIdentity identity = WindowsIdentity.GetCurrent();
                        WindowsPrincipal principal = new WindowsPrincipal(identity);
                        return principal.IsInRole(WindowsBuiltInRole.Administrator);
                    } 


                    /// <summary>
                    /// Show all Network Adapters in the Enable\DisableNetworkAdapter window
                    /// </summary>
                    private void ShowAllNetworkAdapters()
                    {
                        grpNetworkAdapters.Controls.Clear();

                        _allNetworkAdapters = NetworkAdapter.GetAllNetworkAdapter();
                        int i = 0;

                        foreach (NetworkAdapter networkAdapter in _allNetworkAdapters)
                        {
                            i++;
                            UcNetworkAdapter ucNetworkAdapter = new UcNetworkAdapter(
                                networkAdapter, 
                                BtnEnableDisableNetworAdaptetClick, 
                                new Point(10, 30 * i), 
                                grpNetworkAdapters);
                        }
                    }

                    /// <summary>
                    /// Show progress info while enabling or disabling a Network Adapter.
                    /// </summary>
                    private void ShowProgressInfo()
                    {
                        tsslbResult.Text = string.Empty;
                        foreach (Control c in _progressInfoForm.Controls)
                        {
                            if (c is Label)
                            {
                                c.Text = string.Format("{0}[{1}] ({2}) {3}", 
                                    Resources.StatusTextBegin, 
                                    _currentNetworkAdapter.DeviceId, 
                                    _currentNetworkAdapter.Name, 
                                    ((_currentNetworkAdapter.GetNetEnabled() != 1) 
                                    ? Resources.ProgressTextEnableEnd 
                                    : Resources.ProgressTextDisableEnd));
                            }
                        }

                        _progressInfoForm.LocationX = Location.X
                            + (Width - _progressInfoForm.Width) / 2;
                        _progressInfoForm.LocationY = Location.Y
                            + (Height - _progressInfoForm.Height) / 2;

                        _progressInfoForm.ShowDialog();
                    }

                    #endregion

                    #region Event Handler

                    /// <summary>
                    /// Button on click event handler
                    /// Click enable or disable the network adapter
                    /// </summary>
                    /// <param name="sender"></param>
                    /// <param name="e"></param>
                    public void BtnEnableDisableNetworAdaptetClick(object sender, EventArgs e)
                    {
                        Button btnEnableDisableNetworkAdapter = (Button)sender;

                        // The result of enable or disable Network Adapter
                        // result ={-1: Fail;0:Unknow;1:Success}
                        int result = -1;
                        int deviceId = ((int[])btnEnableDisableNetworkAdapter.Tag)[0];

                        Thread showProgressInfoThreadProc = 
                                new Thread(ShowProgressInfo);
                        try
                        {
                            _currentNetworkAdapter = new NetworkAdapter(deviceId);

                            // To avoid the condition of the network adapter netenable change caused 
                            // by any other tool or operation (ex. Disconnected the Media) after you 
                            // start the sample and before you click the enable\disable button.
                            // In this case, the network adapter status shown in windows form is not
                            // meet the real status.

                            // If the network adapters' status is shown corrected,just to enable or 
                            // disable it as usual.
                            if (((int[]) btnEnableDisableNetworkAdapter.Tag)[1]
                                == _currentNetworkAdapter.NetEnabled)
                            {
                                // If Network Adapter NetConnectionStatus in ("Hardware not present",
                                // Hardware disabled","Hardware malfunction","Media disconnected"), 
                                // it will can not be enabled.
                                if (_currentNetworkAdapter.NetEnabled == -1
                                    && (_currentNetworkAdapter.NetConnectionStatus >= 4
                                        && _currentNetworkAdapter.NetConnectionStatus <= 7))
                                {
                                    string error =
                                        String.Format("{0}({1}) [{2}] {3} [{4}]",
                                                      Resources.StatusTextBegin,
                                                      _currentNetworkAdapter.DeviceId,
                                                      Name,
                                                      Resources.CanNotEnableMsg,
                                                      NetworkAdapter.SaNetConnectionStatus
                                                          [_currentNetworkAdapter
                                                          .NetConnectionStatus]);

                                    MessageBox.Show(error,
                                                    Resources.OneCodeCaption,
                                                    MessageBoxButtons.OK,
                                                    MessageBoxIcon.Error);
                                }
                                else
                                {
                                    showProgressInfoThreadProc.Start();

                                    result = _currentNetworkAdapter.EnableOrDisableNetworkAdapter(
                                        (_currentNetworkAdapter.NetEnabled == 1) 
                                        ? "Disable" : "Enable");

                                    showProgressInfoThreadProc.Abort();
                                }
                            }
                            // If the network adapter status are not shown corrected, just to refresh
                            // the form to show the correct network adapter status.
                            else
                            {
                                ShowAllNetworkAdapters();
                                result = 1;
                            }
                        }
                        catch(NullReferenceException)
                        {
                            // If failed to construct _currentNetworkAdapter the result will be fail.
                        }

                        // If successfully enable or disable the Network Adapter
                        if (result > 0)
                        {
                            ShowAllNetworkAdapters();
                            tsslbResult.Text = 
                                string.Format("{0}[{1}] ({2}) {3}", 
                                Resources.StatusTextBegin, 
                                _currentNetworkAdapter.DeviceId, 
                                _currentNetworkAdapter.Name,
                                ((((int[])btnEnableDisableNetworkAdapter.Tag)[1] == 1)
                                ? Resources.StatusTextSuccessDisableEnd 
                                : Resources.StatusTextSuccessEnableEnd)) ;

                            tsslbResult.ForeColor = Color.Green;
                        }
                        else
                        {
                            tsslbResult.Text = 
                                string.Format("{0}[{1}] ({2}) {3}", 
                                Resources.StatusTextBegin, 
                                _currentNetworkAdapter.DeviceId, 
                                _currentNetworkAdapter.Name,
                                ((((int[])btnEnableDisableNetworkAdapter.Tag)[1] == 1) 
                                ? Resources.StatusTextFailDisableEnd 
                                : Resources.StatusTextFailEnableEnd));

                            tsslbResult.ForeColor = Color.Red;
                        }
                    }

                    #endregion 
                }
            }

Ответ 7

Я modfied наилучшее избранное решение от Kamrul Hasan до одного метода и добавил, чтобы дождаться выхода процесса, потому что мой Unit Test код работает быстрее, чем процесс отключает соединение.

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 Измените это: для disable ("netsh", "имя интерфейса набора интерфейсов =" + interfaceName + "admin = DISABLE") и для включения ("netsh", "имя интерфейса набора интерфейсов =" + interfaceName + "admin = ВКЛЮЧИТЬ ") И использовать программу в качестве администратора

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

И использовать Программу в качестве Администратора !!!!!!

Ответ 9

Лучшее решение - отключить все сетевые адаптеры, независимо от имени интерфейса, отключить и включить все сетевые адаптеры, используя этот фрагмент (для работы необходимы права администратора, в противном случае ЕГО НЕ БУДЕТ РАБОТАТЬ):

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