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

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

在搜索同样的东西时发现这个post,所以,这里是答案:)

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

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

msdn上的Win32_NetworkAdapter

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

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

在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 
  namespace CSWMIEnableDisableNetworkAdapter { partial class MainForm { ///  /// Required designer variable. ///  private System.ComponentModel.IContainer components = null; ///  /// Clean up any resources being used. ///  /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code ///  /// Required method for Designer support - do not modify /// the contents of this method with the code editor. ///  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; } } 
  /****************************** 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 ///  /// All Network Adapters in the machine ///  private List _allNetworkAdapters = new List(); ///  /// A ProgressInfo form ///  private ProgressInfoForm _progressInfoForm = new ProgressInfoForm(); ///  /// The Current Operation Network Adapter ///  private NetworkAdapter _currentNetworkAdapter = null; #endregion #region Construct EnableDisableNetworkAdapter ///  /// Construct an EnableDisableNetworkAdapter ///  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 ///  /// You need to run this sample as Administrator /// Check whether the application is run as administrator ///  /// Whether the application is run as administrator private bool isAdministrator() { WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); return principal.IsInRole(WindowsBuiltInRole.Administrator); } ///  /// Show all Network Adapters in the Enable\DisableNetworkAdapter window ///  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); } } ///  /// Show progress info while enabling or disabling a Network Adapter. ///  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 ///  /// Button on click event handler /// Click enable or disable the network adapter ///  ///  ///  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 } } 

我修改了从Kamrul Hasan到一个方法的最佳投票解决方案 ,并添加等待进程的退出,导致我的unit testing代码运行得比进程禁用连接快。

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

对于Windows 10更改此:对于diable(“netsh”,“interface set interface name =”+ interfaceName +“admin = DISABLE”)和对于enable(“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(); } 

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