2008-10-05 14 views
17

Zasadniczo uruchamiam niektóre testy wydajności i nie chcę, aby zewnętrzna sieć była czynnikiem oporu. Szukam sposobów na wyłączenie sieci LAN. Jaki jest skuteczny sposób programowania programowego? Jestem zainteresowany C#. Jeśli ktoś ma fragment kodu, który może doprowadzić punkt do domu, to byłoby fajnie.Jak wyłączyć/włączyć połączenie sieciowe w C#

+0

[Coś podobnego] (http://stackoverflow.com/questions/83756/how-to-programmatically-enabledisable-network-interfaces-windows-xp) zostało omówione. – hayalci

+0

Tak, ale ma aktualny działający kod C#. – Colin

+0

Proszę kliknąć poniższy link. to może ci pomóc. [http://stackoverflow.com/questions/3053372/programmatically-enable-disable-connection](http://stackoverflow.com/questions/3053372/programmatically-enable-disable-connection) –

Odpowiedz

26

Znalazłem ten wątek w poszukiwaniu tego samego, tak, tu jest odpowiedź :)

Najlepszą metodą testowałem w C# używa WMI.

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

Win32_NetworkAdapter on msdn

C# Snippet: (System.Management musi odwoływać się w roztworze, a za pomocą deklaracji)

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

Zauważ, że musiałem uruchomić to jako Administrator (metoda InvokeMethod() nie zwróciła błędu, gdy uruchomiłem go jako peon). – Colin

14

Używając polecenia netsh można włączyć i wyłączyć „ Połączenie lokalne "

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

Po kilku godzinach cierpiących na WMI (najwyraźniej nie każdy adapter oferuje komendę 'Disable' lub coś podobnego),' netsh' działało płynnie przy pierwszym podejściu. – heltonbiker

+1

Należy pamiętać, że to również musi być uruchamiane jako administrator –

+0

To działało miło! Chociaż byłoby to trudne, ale dla mnie to ez. Tnx. – Matarata

1

W VB.Net można również użyć go do przełączania połączenia lokalnego

Uwaga: ja używam go w Windows XP, działa to poprawnie. ale w Windows 7 nie działa poprawnie.

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

inna klasa jest poniżej ... –

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

I modfied się best voted solution z Kamrul Hasan jednej Methode i dodał czekać na wyjściu procesu, bo mój kod przebieg testów jednostkowych szybciej niż proces wyłączyć połączenie.

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

Dla Windows 10 to zmienić: o diable ("netsh", "nazwa zestaw Interface =" + InterfaceName + "admin = DISABLE") i dla umożliwienia ("netsh", „interfejs set interface name =”+ InterfaceName + "admin = ENABLE") I korzystać z programu jako Administrator

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

oraz korzystanie z programu jako Administrator !!!!!!

Powiązane problemy