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.Cómo deshabilitar/habilitar la conexión de red en C#
Respuesta
encontrado este hilo durante la búsqueda de la misma cosa, así, aquí es la respuesta :)
El mejor método Probé en C# utiliza WMI.
http://www.codeproject.com/KB/cs/EverythingInWmi02.aspx
C# Fragmento: (System.Management se indicará 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);
}
}
Tenga en cuenta que tuve que ejecutar esto como administrador (InvokeMethod() no devolvió un error cuando lo ejecuté como peón). – Colin
El uso del sistema de Netsh, puede activar y desactivar “ 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();
}
Después de algunas horas sufriendo con WMI (aparentemente no todos los adaptadores ofrecen el comando 'Disable ', o algo así),' netsh' funcionó sin problemas en el primer intento. – heltonbiker
Tenga en cuenta que esto también debe ejecutarse como administrador –
¡Funcionó bien para mí! Pensé que sería difícil, pero tú lo haces perfecto para mí. Tnx. – Matarata
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
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;
}
}
otra clase está abajo ... –
/****************************** 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
}
}
I modfied la best voted solution de Kamrul Hasan a uno méthode y ha añadido que esperar a la salida del proceso, hacer que mi código de prueba de unidad correr 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();
}
Para Windows 10 Cambio esto: para diable ("nombre de la interfaz conjunto interface =" "netsh" + interfaceName + "admin = APAGADO") y para permitir (interfaz "netsh"," set interface name =" + + interfaceName "admin = ENABLE") y usar el programa como administrador
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();
}
y usar el programa como administrador !!!!!!
- 1. Deshabilitar la conexión de red
- 2. Administración de la conexión de red inalámbrica en C#
- 3. Comprobar conexión de red androide
- 4. Cómo escanear un puerto esperando una conexión en una red
- 5. Detectando la velocidad de conexión de red y el uso de ancho de banda en C#
- 6. Verificación de la conexión de red utilizando Qt 4.4
- 7. socat conexión después de fallo de la red
- 8. Detectando el estado de la red (conectado - desconectado) en C#
- 9. C# impresión en red
- 10. ¿Cómo puedo simular una conexión de red lenta
- 11. IOException: El adaptador de red no pudo establecer la conexión
- 12. ¿Cómo verifico si tengo una conexión de red?
- 13. ¿Cómo detectar la conexión a Internet que funciona en C#?
- 14. nodejs vuelven a conectar conexión a la red
- 15. Cómo verificar la conectividad de red en Object-C
- 16. Se intentó una operación en una conexión de red inexistente
- 17. ¿Cómo puedo controlar el estado de la conexión de red en Android?
- 18. ¿Se conecta a la red una conexión a localhost?
- 19. ¿Cómo saber que la conexión TCP está cerrada en el paquete de red Golang?
- 20. Cómo generar paquetes de red con C/C++
- 21. Conectarse a una red inalámbrica en C#
- 22. EC2 Red de error: Tiempo de espera de conexión
- 23. Copia de archivos a través de una conexión intermitente Red
- 24. Conexión SVN + SSH que genera el error 210002, conexión de red cerrada inesperadamente
- 25. ¿Cómo falsificar los cambios de tipo de conexión de red en el simulador de iOS?
- 26. ¿Cómo detectar la conexión del teclado externo en Object-C?
- 27. Uso Directory.Exists en una carpeta de red cuando la red está abajo
- 28. red TCPIP con C#
- 29. programación C# red
- 30. Cómo iniciar una conexión de red local a través de programmically zona Wi-Fi en Android?
[Algo similar] (http://stackoverflow.com/questions/83756/how-to-programmatically-enabledisable-network-interfaces-windows-xp) se ha debatido. – hayalci
Sí, pero esto tiene código C# real de trabajo. – Colin
Por favor, siga el enlace a continuación. te puede ayudar. [http://stackoverflow.com/questions/3053372/programmatically-enable-disable-connection](http://stackoverflow.com/questions/3053372/programmatically- habilitable-disable-connection) –