C# 啟用或禁用網卡 2種方法

來源:互聯網
上載者:User

        [DllImport("wininet.dll")]
        private extern static bool InternetCheckConnection(String url, int flag, int ReservedValue);
        /// <summary>
        /// 第一步.檢測外網的一個網站,如www.baidu.com
        /// </summary>
        /// <returns></returns>
        public bool GetExtranet()
        {
            bool extranet = false;
            try
            {
                if (InternetCheckConnection("http://www.baidu.com/", 1, 0).Equals(false))
                {
                    extranet = false;
                }
                else
                {
                    extranet = true;
                }
            }
            catch (Exception e)
            {
                e.ToString();
            }
            return extranet;
        }

1

//禁用 SetNetworkAdapter(False)    
//啟用 SetNetworkAdapter(True)    
//添加引用system32\shell32.dll    
private static bool SetNetworkAdapter(bool status)    
{    
     const string discVerb = "停用(&B)"; // "停用(&B)";    
     const string connVerb = "啟用(&A)"; // "啟用(&A)";    
     const string network = "網路連接"; //"網路連接";    
     const string networkConnection = "VMware Network Adapter VMnet1"; // "本地串連"    
  
     string sVerb = null;    
  
     if (status)    
     {    
         sVerb = connVerb;    
     }    
     else    
     {    
         sVerb = discVerb;    
     }    
  
     Shell32.Shell sh = new Shell32.Shell();    
     Shell32.Folder folder = sh.NameSpace(Shell32.ShellSpecialFolderConstants.ssfCONTROLS);    
  
     try    
     {    
         //進入控制台的所有選項    
         foreach (Shell32.FolderItem myItem in folder.Items())    
         {    
             //進入網路連接    
             if (myItem.Name == network)    
             {    
                 Shell32.Folder fd = (Shell32.Folder)myItem.GetFolder;    
                 foreach (Shell32.FolderItem fi in fd.Items())    
                 {    
                     //找到本地串連    
                     if ((fi.Name == networkConnection))    
                     {    
                         //找本地串連的所有右鍵功能菜單    
                         foreach (Shell32.FolderItemVerb Fib in fi.Verbs())    
                         {    
                             if (Fib.Name == sVerb)    
                             {    
                                 Fib.DoIt();    
                                 return true;    
                             }    
                         }    
                     }    
                 }    
             }    
         }    
     }    
     catch (Exception e)    
     {    
         Console.WriteLine(e.Message);    
         return false;    
     }    
     return true;    
}  

======

2

c#中禁用和開啟網卡

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Management;

using System.Collections;

namespace NetWorkControl

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

            NetWorkList();

        }

        /// <summary>

        /// 網卡列表

        /// </summary>

        public void NetWorkList()

        {

            string manage = "SELECT * From Win32_NetworkAdapter";

            ManagementObjectSearcher searcher = new ManagementObjectSearcher(manage);

            ManagementObjectCollection collection = searcher.Get();

            List<string> netWorkList = new List<string>();

            foreach (ManagementObject obj in collection)

            {

                netWorkList.Add(obj["Name"].ToString());

                

            }

           this.cmbNetWork.DataSource = netWorkList;

        }

        /// <summary>

        /// 禁用網卡

        /// </summary>5

        /// <param name="netWorkName">網卡名</param>

        /// <returns></returns>

        public bool DisableNetWork(ManagementObject network)

        {

            try

            {

                network.InvokeMethod("Disable", null);

                return true;

            }

            catch

            {

                return false;

            }

        }

        /// <summary>

        /// 啟用網卡

        /// </summary>

        /// <param name="netWorkName">網卡名</param>

        /// <returns></returns>

        public bool EnableNetWork(ManagementObject network)

        {

            try

            {

                network.InvokeMethod("Enable", null );

                return true;

            }

            catch

            {

                return false;

            }

            

        }

        /// <summary>

        /// 網卡狀態

        /// </summary>

        /// <param name="netWorkName">網卡名</param>

        /// <returns></returns>

        public bool NetWorkState(string netWorkName)

        {

            string netState = "SELECT * From Win32_NetworkAdapter";

            ManagementObjectSearcher searcher = new ManagementObjectSearcher(netState);

            ManagementObjectCollection collection = searcher.Get();

            foreach (ManagementObject manage in collection)

            {

                if (manage["Name"].ToString() == netWorkName )

                {

                    return true;

                }

            }

            return false;

        }

        /// <summary>

        /// 得到指定網卡

        /// </summary>

        /// <param name="networkname">網卡名字</param>

        /// <returns></returns>

        public ManagementObject NetWork(string networkname)

        {

            string netState = "SELECT * From Win32_NetworkAdapter";

            ManagementObjectSearcher searcher = new ManagementObjectSearcher(netState);

            ManagementObjectCollection collection = searcher.Get();

            foreach (ManagementObject manage in collection)

            {

                if (manage["Name"].ToString() == networkname)

                {

                    return manage;

                }

            }

            

            return null;

        }

        private void btnStart_Click(object sender, EventArgs e)

        {

            if (NetWorkState(this.cmbNetWork.SelectedValue.ToString()))

            {

                if (!EnableNetWork(NetWork(this.cmbNetWork.SelectedValue.ToString())))

                {

                    MessageBox.Show("開啟網卡失敗!");

                }

                else

                {

                    MessageBox.Show("開啟網卡成功!");

                }

            }

            else

            {

                MessageBox.Show("網卡己開啟!");

            }

            NetWorkList();

        }

        private void btnStop_Click(object sender, EventArgs e)

        {

            if (NetWorkState(this.cmbNetWork.SelectedValue.ToString()))

            {

                if (!DisableNetWork(NetWork(this.cmbNetWork.SelectedValue.ToString())))

                {

                    MessageBox.Show("禁用網卡失敗!");

                }

                else

                {

                    MessageBox.Show("禁用網卡成功!");

                }

            }

            else

            {

                MessageBox.Show("網卡己禁用!");

            }

            NetWorkList();

        }

    }

}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.