C#實(shí)現(xiàn)可以自由切換IP.

2010-08-28 10:50:44來(lái)源:西部e網(wǎng)作者:

源代碼如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Xml;
using System.Management;
using System.Text.RegularExpressions;
using System.Net;

namespace ChangeIP
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //perferred configuration.
            this.textBox1.Text = ConfigurationManager.AppSettings.Get("PerferredIP").Trim();
            this.textBox2.Text = ConfigurationManager.AppSettings.Get("PerferredMask").Trim();
            this.textBox3.Text = ConfigurationManager.AppSettings.Get("PerferredGateway").Trim();
            this.textBox4.Text = ConfigurationManager.AppSettings.Get("PerferredDNS1").Trim();
            this.textBox5.Text = ConfigurationManager.AppSettings.Get("PerferredDNS2").Trim();
            //spare configuration.
            this.textBox10.Text = ConfigurationManager.AppSettings.Get("SpareIP").Trim();
            this.textBox9.Text = ConfigurationManager.AppSettings.Get("SpareMask").Trim();
            this.textBox8.Text = ConfigurationManager.AppSettings.Get("SpareGateway").Trim();
            this.textBox7.Text = ConfigurationManager.AppSettings.Get("SpareDNS1").Trim();
            this.textBox6.Text = ConfigurationManager.AppSettings.Get("SpareDNS2").Trim();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Regex Rx = new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}");
            Regex Rx1 = new Regex(@"[a-zA-Z]+");
            if (!(Rx.IsMatch(this.textBox1.Text.ToString().Trim()) && Rx.IsMatch(this.textBox2.Text.ToString().Trim()) && Rx.IsMatch(this.textBox3.Text.ToString().Trim()) && Rx.IsMatch(this.textBox4.Text.ToString().Trim()) && Rx.IsMatch(this.textBox5.Text.ToString().Trim())))
            {
                MessageBox.Show("Format is inaccurate.", "Switch IP address", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (Rx1.IsMatch(this.textBox1.Text.ToString().Trim())||Rx1.IsMatch(this.textBox2.Text.ToString().Trim())||Rx1.IsMatch(this.textBox3.Text.ToString().Trim())||Rx1.IsMatch(this.textBox4.Text.ToString().Trim())||Rx1.IsMatch(this.textBox5.Text.ToString().Trim()))
            {
                MessageBox.Show("Con't contain character [a-z][A-Z].", "Switch IP address", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            try
            {
                string FileName = Application.StartupPath + "\\ChangeIP.exe.config";
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(FileName);
                XmlNodeList nodes = xmldoc.GetElementsByTagName("add");
                if (nodes.Count == 0)
                    return;
                foreach (XmlNode mynode in nodes)
                {
                    switch (mynode.Attributes["key"].Value)
                    {
                        case "PerferredIP":
                            {
                                mynode.Attributes["value"].Value = this.textBox1.Text.ToString().Trim();
                                break;
                            }
                        case "PerferredMask":
                            {
                                mynode.Attributes["value"].Value = this.textBox2.Text.ToString().Trim();
                                break;
                            }
                        case "PerferredGateway":
                            {
                                mynode.Attributes["value"].Value = this.textBox3.Text.ToString().Trim();
                                break;
                            }
                        case "PerferredDNS1":
                            {
                                mynode.Attributes["value"].Value = this.textBox4.Text.ToString().Trim();
                                break;
                            }
                        case "PerferredDNS2":
                            {
                                mynode.Attributes["value"].Value = this.textBox5.Text.ToString().Trim();
                                break;
                            }
                    }
                }
                xmldoc.Save(FileName);
                MessageBox.Show("Your configuration have been saved.", "Switch IP address", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message, "Switch IP address", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Regex Rx = new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}");
            Regex Rx1 = new Regex(@"[a-zA-Z]+");
            if (!(Rx.IsMatch(this.textBox10.Text.ToString().Trim()) && Rx.IsMatch(this.textBox9.Text.ToString().Trim()) && Rx.IsMatch(this.textBox8.Text.ToString().Trim()) && Rx.IsMatch(this.textBox7.Text.ToString().Trim()) && Rx.IsMatch(this.textBox6.Text.ToString().Trim())))
            {
                MessageBox.Show("Format is inaccurate.", "Switch IP address", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (Rx1.IsMatch(this.textBox10.Text.ToString().Trim()) || Rx1.IsMatch(this.textBox9.Text.ToString().Trim()) || Rx1.IsMatch(this.textBox8.Text.ToString().Trim()) || Rx1.IsMatch(this.textBox7.Text.ToString().Trim()) || Rx1.IsMatch(this.textBox6.Text.ToString().Trim()))
            {
                MessageBox.Show("Con't contain character [a-z][A-Z].", "Switch IP address", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            try
            {
                string FileName = Application.StartupPath + "\\ChangeIP.exe.config";
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(FileName);
                XmlNodeList nodes = xmldoc.GetElementsByTagName("add");
                if (nodes.Count == 0)
                    return;
                foreach (XmlNode mynode in nodes)
                {
                    switch (mynode.Attributes["key"].Value)
                    {
                        case "SpareIP":
                            {
                                mynode.Attributes["value"].Value = this.textBox10.Text.ToString().Trim();
                                break;
                            }
                        case "SpareMask":
                            {
                                mynode.Attributes["value"].Value = this.textBox9.Text.ToString().Trim();
                                break;
                            }
                        case "SpareGateway":
                            {
                                mynode.Attributes["value"].Value = this.textBox8.Text.ToString().Trim();
                                break;
                            }
                        case "SpareDNS1":
                            {
                                mynode.Attributes["value"].Value = this.textBox7.Text.ToString().Trim();
                                break;
                            }
                        case "SpareDNS2":
                            {
                                mynode.Attributes["value"].Value = this.textBox6.Text.ToString().Trim();
                                break;
                            }
                    }
                }
                xmldoc.Save(FileName);
                MessageBox.Show("Your configuration have been saved.", "Switch IP address", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message,"Switch IP address",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                ManagementBaseObject Inpra = null;
                ManagementBaseObject OutPra = null;
                ManagementClass MC = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection Moc = MC.GetInstances();

                foreach (ManagementObject mo in Moc)
                {
                    if (!(bool)mo["IPEnabled"])
                        continue;

                    Inpra = mo.GetMethodParameters("EnableStatic");
                    Inpra["IPAddress"] = new string[] { this.textBox1.Text.ToString().Trim() };

                    Inpra["SubnetMask"] = new string[] { this.textBox2.Text.ToString().Trim() };
                    OutPra = mo.InvokeMethod("EnableStatic", Inpra, null);

                    Inpra = mo.GetMethodParameters("SetGateways");
                    Inpra["DefaultIPGateway"] = new string[] { this.textBox3.Text.ToString().Trim() };
                    OutPra = mo.InvokeMethod("SetGateways", Inpra, null);

                    Inpra = mo.GetMethodParameters("SetDNSServerSearchOrder");
                    Inpra["DNSServerSearchOrder"] = new string[] { this.textBox4.Text.ToString().Trim(), this.textBox5.Text.ToString().Trim() };
                    OutPra = mo.InvokeMethod("SetDNSServerSearchOrder", Inpra, null);

                    break;
                }

                IPHostEntry oIPHost = Dns.GetHostEntry(Environment.MachineName);
                if (oIPHost.AddressList.Length > 0)
                { this.label11.Text = "Current IP address is: "+oIPHost.AddressList[0].ToString(); }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Switch IP address", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                ManagementBaseObject Inpra = null;
                ManagementBaseObject OutPra = null;
                ManagementClass MC = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection Moc = MC.GetInstances();

                foreach (ManagementObject mo in Moc)
                {
                    if (!(bool)mo["IPEnabled"])
                        continue;

                    Inpra = mo.GetMethodParameters("EnableStatic");
                    Inpra["IPAddress"] = new string[] { this.textBox10.Text.ToString().Trim() };

                    Inpra["SubnetMask"] = new string[] { this.textBox9.Text.ToString().Trim() };
                    OutPra = mo.InvokeMethod("EnableStatic", Inpra, null);

                    Inpra = mo.GetMethodParameters("SetGateways");
                    Inpra["DefaultIPGateway"] = new string[] { this.textBox8.Text.ToString().Trim() };
                    OutPra = mo.InvokeMethod("SetGateways", Inpra, null);

                    Inpra = mo.GetMethodParameters("SetDNSServerSearchOrder");
                    Inpra["DNSServerSearchOrder"] = new string[] { this.textBox7.Text.ToString().Trim(), this.textBox6.Text.ToString().Trim() };
                    OutPra = mo.InvokeMethod("SetDNSServerSearchOrder", Inpra, null);

                    break;
                }

                IPHostEntry oIPHost = Dns.GetHostEntry(Environment.MachineName);
                if (oIPHost.AddressList.Length > 0)
                { this.label12.Text = "Current IP address is: " + oIPHost.AddressList[0].ToString(); }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Switch IP address", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

原文地址: http://www.cnblogs.com/Roger52027/archive/2006/12/28/605898.html

關(guān)鍵詞:C#