visual tiempo studio permiten modificar mientras esta ejecutando ejecucion editar continuar codigo cambios c# networking lan

tiempo - Cómo deshabilitar/habilitar la conexión de red en c#



modificar codigo en tiempo de ejecucion c# (6)

Encontré este hilo mientras buscaba lo mismo, así que, aquí está la respuesta :)

El mejor método que probé en C # usa WMI.

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

Win32_NetworkAdapter en msdn

Fragmento de C #: (se debe hacer referencia a System.Management en la solución y en el uso de declaraciones)

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

Básicamente estoy ejecutando algunas pruebas de rendimiento y no quiero que la red externa sea el factor de arrastre. Estoy buscando formas de desactivar la red LAN. ¿Cuál es una forma efectiva de hacerlo programáticamente? Estoy interesado en c #. Si alguien tiene un fragmento de código que puede llevar el punto a casa, sería genial.


En VB.Net, también puede usarlo para alternar la conexión de área local

Nota: yo mismo lo uso en Windows XP, funciona aquí correctamente. pero en Windows 7 no funciona correctamente.

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


Usando el comando netsh, puede habilitar y deshabilitar "Conexión de área local"

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


/****************************** 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 } }


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


Modifiqué la solución mejor votada de Kamrul Hasan a un método y la agregué para esperar la salida del proceso, porque mi código de Prueba de Unidad se ejecuta más rápido que el proceso de desactivar la conexión.

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