当前位置: 代码迷 >> C# >> c#批改本地连接工具 ip地址,dns,网关,子网掩码
  详细解决方案

c#批改本地连接工具 ip地址,dns,网关,子网掩码

热度:511   发布时间:2016-05-05 02:56:56.0
c#修改本地连接工具 ip地址,dns,网关,子网掩码

//Form1类后台    

    #region 加载配置文件中的信息
        /// <summary>
        /// 加载配置文件中的信息
        /// </summary>
        protected void loadConfig()
        {
            cf.fileName = AppDomain.CurrentDomain.BaseDirectory + "\\config.ini";
            txtIP.Text = cf["ip地址"];
            txtSubMark.Text = cf["子网掩码"];
            txtGateWay.Text = cf["默认网关"];
            txtDNS1.Text = cf["主DNS"];
            txtDNS2.Text = cf["备用DNS"];
        }
        #endregion

        #region 设置ip信息到网卡
        private void btnSettingNetwork_Click(object sender, EventArgs e)
        {
           
            try
            {
                if (!IsIpaddress(txtIP.Text.Trim()))
                {
                    MessageBox.Show("ip格式不正确!"); return;
                }
                if (!IsIpaddress(txtSubMark.Text.Trim()))
                {
                    MessageBox.Show("子网掩码格式不正确!"); return;
                }
                if (!IsIpaddress(txtGateWay.Text.Trim()))
                {
                    MessageBox.Show("网关格式不正确!"); return;
                }
                if (!IsIpaddress(txtDNS1.Text.Trim()))
                {
                    MessageBox.Show("DNS1格式不正确!"); return;
                }
                if (!IsIpaddress(txtDNS2.Text.Trim()))
                {
                    MessageBox.Show("DNS2格式不正确!"); return;
                }
                string[] ip = new string[] {txtIP.Text.Trim() };
                string[] SubMark = new string[] {txtSubMark.Text.Trim() };
                string[] GateWay = new string[] {txtGateWay.Text.Trim() };
                string[] DNS = new string[] {txtDNS1.Text.Trim(),txtDNS2.Text.Trim() };
                SetIpInfo(ip, SubMark, GateWay, DNS);
                cf["ip地址"] = txtIP.Text.Trim();
                cf["子网掩码"] = txtSubMark.Text.Trim();
                cf["默认网关"] = txtGateWay.Text.Trim();
                cf["主DNS"] = txtDNS1.Text.Trim();
                cf["备用DNS"] = txtDNS2.Text.Trim();
                MessageBox.Show("ip信息设置成功!","成功提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }
            catch(Exception er)
            {
                MessageBox.Show("设置出错:"+er.Message,"出错提示",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
        }

        protected void SetIpInfo(string []ip,string []SubMark,string []GateWay,string []DNS)
        {
            ManagementBaseObject inPar = null;
            ManagementBaseObject outPar = null;
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if (!(bool)mo["IPEnabled"]) continue;
                inPar = mo.GetMethodParameters("EnableStatic");
                inPar["IPAddress"] = ip;//ip地址
                inPar["SubnetMask"] =SubMark; //子网掩码
                mo.InvokeMethod("EnableStatic", inPar, null);//执行

                inPar = mo.GetMethodParameters("SetGateways");
                inPar["DefaultIPGateway"] = GateWay; //设置网关地址 1.网关;2.备用网关
                outPar = mo.InvokeMethod("SetGateways", inPar, null);//执行

                inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
                inPar["DNSServerSearchOrder"] = DNS; //设置DNS  1.DNS 2.备用DNS
                mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);// 执行
                break; //只设置一张网卡,不能多张。
            }
        }

        #endregion

        #region 从网卡获取ip设置信息
        /// <summary>
        /// 从网卡获取ip设置信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetFromNetwork_Click(object sender, EventArgs e)
        {
            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface adapter in nics)
            {
                bool Pd1 = (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet); //判断是否是以太网连接
                if (Pd1)
                {
                    IPInterfaceProperties ip = adapter.GetIPProperties();     //IP配置信息
                    if (ip.UnicastAddresses.Count > 0)
                    {
                        txtIP.Text = ip.UnicastAddresses[0].Address.ToString();//IP地址
                        txtSubMark.Text = ip.UnicastAddresses[0].IPv4Mask.ToString();//子网掩码

                    }
                    if (ip.GatewayAddresses.Count > 0)
                    {
                        txtGateWay.Text = ip.GatewayAddresses[0].Address.ToString();//默认网关
                    }
                    int DnsCount = ip.DnsAddresses.Count;
                    Console.WriteLine("DNS服务器地址:");
                    if (DnsCount > 0)
                    {
                        try
                        {
                            txtDNS1.Text = ip.DnsAddresses[0].ToString(); //主DNS
                            txtDNS2.Text = ip.DnsAddresses[1].ToString(); //备用DNS地址
                        }
                        catch(Exception er)
                        {
                            throw er;
                        }
                    }
                }
            }
        }
        #endregion

        #region 判断是否是正确的ip地址
        /// <summary>
        /// 判断是否是正确的ip地址
        /// </summary>
        /// <param name="ipaddress"></param>
        /// <returns></returns>
        protected bool IsIpaddress(string ipaddress)
        {
            string[] nums = ipaddress.Split('.');
            if (nums.Length != 4) return false;
            foreach (string num in nums)
            {
                if ( Convert.ToInt32(num) < 0 || Convert.ToInt32(num) > 255) return false;
            }
            return true;
        }
        #endregion

        #region Form1_Load
        private void Form1_Load(object sender, EventArgs e)
        {
            loadConfig();
        }
        #endregion

 

//config类

    public class ConfigFile : IConfig
    {
        // Fields
        private string _fileName;
        private static ConfigFile _Instance;

        // Methods
        private ConfigFile()
        {
        }

        public bool CreateFile()
        {
            bool flag = false;
            if (File.Exists(this.fileName))
            {
                return flag;
            }
            using (File.Create(this.fileName))
            {
            }
            return true;
        }

        public bool KeyExists(string Key)
        {
            return (this.Keys as ICollection<string>).Contains(Key);
        }

        // Properties
        public string fileName
        {
            get
            {
                return this._fileName;
            }
            set
            {
                this._fileName = value;
            }
        }

        public static ConfigFile Instanse
        {
            get
            {
                if (_Instance == null)
                {
                    _Instance = new ConfigFile();
                }
                return _Instance;
            }
        }

        public string this[string Key]
        {
            get
            {
                if (!this.CreateFile())
                {
                    foreach (string str in File.ReadAllLines(this.fileName, Encoding.UTF8))
                    {
                        Match match = Regex.Match(str, @"(\w+)=([\w\W]+)");
                        string str2 = match.Groups[1].Value;
                        string str3 = match.Groups[2].Value;
                        if (str2 == Key)
                        {
                            return str3;
                        }
                    }
                }
                return "";
            }
            set
            {
                if (this.CreateFile())
                {
                    File.AppendAllText(this.fileName, Key + "=" + value + "\r\n");
                }
                else
                {
                    string[] contents = File.ReadAllLines(this.fileName, Encoding.UTF8);
                    for (int i = 0; i < contents.Length; i++)
                    {
                        string input = contents[i];
                        Match match = Regex.Match(input, @"(\w+)=(\w+)");
                        string str2 = match.Groups[1].Value;
                        string text1 = match.Groups[2].Value;
                        if (str2 == Key)
                        {
                            contents[i] = str2 + "=" + value;
                            File.WriteAllLines(this.fileName, contents);
                            return;
                        }
                    }
                    File.AppendAllText(this.fileName, Key + "=" + value + "\r\n");
                }
            }
        }

        public string[] Keys
        {
            get
            {
                List<string> list = new List<string>();
                if (!this.CreateFile())
                {
                    foreach (string str in File.ReadAllLines(this.fileName, Encoding.UTF8))
                    {
                        string item = Regex.Match(str, @"(\w+)=(\w+)").Groups[1].Value;
                        list.Add(item);
                    }
                }
                return list.ToArray();
            }
        }
    }

 

    public interface IConfig
    {
        // Methods
        bool KeyExists(string Key);

        // Properties
        string this[string Key] { get; set; }
        string[] Keys { get; }
    }

 效果:

  相关解决方案