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

效果:

c#修改本地连接工具 ip地址,dns,网关,子网掩码的更多相关文章

  1. CentOS 网络设置修改 指定IP地址 DNS 网关(转)

    CentOS 网络设置修改 指定IP地址 DNS 网关(实测 笔记)   环境: 系统硬件:vmware vsphere (CPU:2*4核,内存2G) 系统版本:Centos-6.5-x86_64 ...

  2. CentOS 修改IP地址, DNS, 网关

    一.CentOS 修改IP地址 修改对应网卡的IP地址的配置文件# vi /etc/sysconfig/network-scripts/ifcfg-eth0 修改以下内容DEVICE=eth0 #描述 ...

  3. CentOS 6 网络设置修改 指定IP地址 DNS 网关

    环境: 系统硬件:vmware vsphere (CPU:2*4核,内存2G) 系统版本:Centos-6.5-x86_64 路由器网关:192.168.1.1 步骤: 1.查看网络MAC地址 [ro ...

  4. Linux系统下修改IP地址、网关、DNS的基本方法

    临时修改IP地址.网关.主机名.DNS,马上生效,无需重启(重启后失效) 1.修改主机名 #hostname Slyar 2.修改IP地址(eth0为网卡名称) #ifconfig eth0 192. ...

  5. Linux学习笔记(10)linux网络管理与配置之一——主机名与IP地址,DNS解析与本地hosts解析(1-4)

    Linux学习笔记(10)linux网络管理与配置之一——主机名与IP地址,DNS解析与本地hosts解析 大纲目录 0.常用linux基础网络命令 1.配置主机名 2.配置网卡信息与IP地址 3.配 ...

  6. linux下设置ip地址 gw网关,dns的方法

    本文介绍下,在linux中设置IP地址.网关.dns的方法,有需要的朋友作个参考吧.   设置linux网络的方法有两种:第一种:使用命令修改(直接即时生效) 复制代码代码示例: ip and net ...

  7. Linux 修改 IP地址 和 网关

    修改IP地址和网关是很常见的操作,在做相关实验的时候,如果没有设置好,会带来很多不必要的麻烦.. 1. 修改IP地址vi /etc/sysconfig/network-scripts/ifcfg-et ...

  8. IP:192.168.21.173 子网掩码:255.255.255.0 网关:192.168.21.2 DNS:8.8.8.8 8.8.4.4 1、设置IP地址、网关 ee /etc/rc.conf #编辑 ifconfig_em0="inet 192.168.21.173 netmask 255

    IP:192.168.21.173子网掩码:255.255.255.0网关:192.168.21.2DNS:8.8.8.88.8.4.41.设置IP地址.网关ee /etc/rc.conf #编辑if ...

  9. IP地址/掩码/网关/DNS的设置与工作原理(转)

    现在互联网飞速发展,工作中生活中上不了网的计算机是不可想象的,而电脑系统网络设置中的IP地址.子网掩码.默认网关及DNS服务器,怎么理解,它们是如何工作的,下面做个简单介绍. 通常的上网方式,是打开I ...

随机推荐

  1. 表格table常见的边框设置和初步的立体效果

    做网页时经常会遇到表格,常见的表格如下: <style type="text/css"> .tbtest0 { width:500px; height:200px; b ...

  2. 让footer在底部(测试它人方法)

    要求:网页布局中,页脚在底部.内容不够一页时,在底部.内容超过一页时,出现卷动条,页脚也在被挤到底部 1.测试的这个文章介绍的办法   链接: http://www.cnblogs.com/cheny ...

  3. 数据链路层-点对点协议PPP

    在通信质量较差的年代,在数据链路层使用可靠传输协议曾是一个好的办法.因此,能实现可靠传输的高级数据链路控制HDLC(High-Level Data Link Control)就称为当时比较流行的数据链 ...

  4. eclipse修改字体

    修改xml字体: window→Preferences→General→Colors and Fonts→Basic→Text Font

  5. 距离顶部估计像素,显示div!

    <html> <head> <title>slide</title> <style type="text/css"> # ...

  6. 硬盘安装ubuntu

    本文记录在能够启动到GRUB2启动菜单的前提下硬盘安装ubuntu的方法. 14.04和16.04测试可用. 假设镜像文件放在GPT第一个分区,文件名为ubuntu.iso. 启动到GRUB2菜单后, ...

  7. 学习memcached的一个网站

    http://www.ibm.com/developerworks/cn/java/j-memcached1/#resources

  8. NSString、NSData、char* 类型之间的转换-备

    1. NSString转化为UNICODE String: (NSString*)fname = @“Test”; char fnameStr[10]; memcpy(fnameStr, [fname ...

  9. 使用 Mockito 单元测试 – 教程

    tanyuanji@126.com 版本历史 - - - - 使用 Mockito 进行测试 该教程主要讲解 Mockito 框架在Eclipse IDE 中的使用   目录 tanyuanji@12 ...

  10. oracle ed命令

    今天在弄oracle sqlplus的时候需要写一个存储过程,用ed进入之后,退不出来了. 从网上找到下面的方法处理:   如何退出sqlplus ed操作   今天进入sqlplus ,执行完语句后 ...