当前位置:  开发笔记 > 编程语言 > 正文

如何使用C#中的代码更改网络设置(IP地址,DNS,WINS,主机名)

如何解决《如何使用C#中的代码更改网络设置(IP地址,DNS,WINS,主机名)》经验,为你挑选了3个好方法。

我正在为一台机器开发一个向导,用作其他机器的备份.当它替换现有机器时,需要设置其IP地址,DNS,WINS和主机名以匹配要更换的机器.

在.net(C#)中是否有一个库允许我以编程方式执行此操作?

有多个NIC,每个都需要单独设置.

编辑

谢谢TimothyP的例子.它让我在正确的轨道上移动,快速回复很棒.

谢谢balexandre.你的代码很完美.我很匆忙,并且已经修改了TimothyP链接的示例,但我希望能早点使用您的代码.

我还开发了一个例程,使用类似的技术来更改计算机名称.我将来会发布它,所以如果你想了解更新,请订阅这个问题RSS feed.我可能会在今天晚些时候或周一经过一些清理后得到它.



1> balexandre..:

刚刚在几分钟内做到这一点:

using System;
using System.Management;

namespace WindowsFormsApplication_CS
{
  class NetworkManagement
  {
    public void setIP(string ip_address, string subnet_mask)
    {
      ManagementClass objMC =
        new ManagementClass("Win32_NetworkAdapterConfiguration");
      ManagementObjectCollection objMOC = objMC.GetInstances();

      foreach (ManagementObject objMO in objMOC)
      {
        if ((bool)objMO["IPEnabled"])
        {
          ManagementBaseObject setIP;
          ManagementBaseObject newIP =
            objMO.GetMethodParameters("EnableStatic");

          newIP["IPAddress"] = new string[] { ip_address };
          newIP["SubnetMask"] = new string[] { subnet_mask };

          setIP = objMO.InvokeMethod("EnableStatic", newIP, null);
        }
      }
    }

    public void setGateway(string gateway)
    {
      ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
      ManagementObjectCollection objMOC = objMC.GetInstances();

      foreach (ManagementObject objMO in objMOC)
      {
        if ((bool)objMO["IPEnabled"])
        {
          ManagementBaseObject setGateway;
          ManagementBaseObject newGateway =
            objMO.GetMethodParameters("SetGateways");

          newGateway["DefaultIPGateway"] = new string[] { gateway };
          newGateway["GatewayCostMetric"] = new int[] { 1 };

          setGateway = objMO.InvokeMethod("SetGateways", newGateway, null);
        }
      }
    }

    public void setDNS(string NIC, string DNS)
    {
      ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
      ManagementObjectCollection objMOC = objMC.GetInstances();

      foreach (ManagementObject objMO in objMOC)
      {
        if ((bool)objMO["IPEnabled"])
        {
          // if you are using the System.Net.NetworkInformation.NetworkInterface
          // you'll need to change this line to
          // if (objMO["Caption"].ToString().Contains(NIC))
          // and pass in the Description property instead of the name 
          if (objMO["Caption"].Equals(NIC))
          {
            ManagementBaseObject newDNS =
              objMO.GetMethodParameters("SetDNSServerSearchOrder");
            newDNS["DNSServerSearchOrder"] = DNS.Split(',');
            ManagementBaseObject setDNS =
              objMO.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
          }
        }
      }
    }

    public void setWINS(string NIC, string priWINS, string secWINS)
    {
      ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
      ManagementObjectCollection objMOC = objMC.GetInstances();

      foreach (ManagementObject objMO in objMOC)
      {
        if ((bool)objMO["IPEnabled"])
        {
          if (objMO["Caption"].Equals(NIC))
          {
            ManagementBaseObject setWINS;
            ManagementBaseObject wins =
            objMO.GetMethodParameters("SetWINSServer");
            wins.SetPropertyValue("WINSPrimaryServer", priWINS);
            wins.SetPropertyValue("WINSSecondaryServer", secWINS);

            setWINS = objMO.InvokeMethod("SetWINSServer", wins, null);
          }
        }
      }
    } 
  }
}


对于那些感兴趣的人,您可以在此处找到此ManagementObject上所有属性和方法的列表:http://msdn.microsoft.com/en-us/library/aa394217.aspx
就像EnableStatic一样,有没有办法以编程方式将IP切换回动态?EnableDynamic?我想构建一个工具,只需点击一下即可在静态和动态IP之间切换.谢谢.
如果其他人想知道,要将DNS服务器重置为"自动",只需将DNSSearverSearchOrder设置为null.例如newDNS ["DNSServerSearchOrder"] = null;

2> Marc..:

将balexandre中的代码重构一点,以便处理对象并使用C#3.5+的新语言功能(Linq,var等).还将变量重命名为更有意义的名称.我还合并了一些函数,以便能够以更少的WMI交互进行更多配置.我删除了WINS代码,因为我不再需要配置WINS.如果需要,可以随意添加WINS代码.

对于任何人都喜欢使用重构/现代化代码的情况,我把它放回社区.

/// 
/// Helper class to set networking configuration like IP address, DNS servers, etc.
/// 
public class NetworkConfigurator
{
    /// 
    /// Set's a new IP Address and it's Submask of the local machine
    /// 
    /// The IP Address
    /// The Submask IP Address
    /// The gateway.
    /// Requires a reference to the System.Management namespace
    public void SetIP(string ipAddress, string subnetMask, string gateway)
    {
        using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
        {
            using (var networkConfigs = networkConfigMng.GetInstances())
            {
                foreach (var managementObject in networkConfigs.Cast().Where(managementObject => (bool)managementObject["IPEnabled"]))
                {
                    using (var newIP = managementObject.GetMethodParameters("EnableStatic"))
                    {
                        // Set new IP address and subnet if needed
                        if ((!String.IsNullOrEmpty(ipAddress)) || (!String.IsNullOrEmpty(subnetMask)))
                        {
                            if (!String.IsNullOrEmpty(ipAddress))
                            {
                                newIP["IPAddress"] = new[] { ipAddress };
                            }

                            if (!String.IsNullOrEmpty(subnetMask))
                            {
                                newIP["SubnetMask"] = new[] { subnetMask };
                            }

                            managementObject.InvokeMethod("EnableStatic", newIP, null);
                        }

                        // Set mew gateway if needed
                        if (!String.IsNullOrEmpty(gateway))
                        {
                            using (var newGateway = managementObject.GetMethodParameters("SetGateways"))
                            {
                                newGateway["DefaultIPGateway"] = new[] { gateway };
                                newGateway["GatewayCostMetric"] = new[] { 1 };
                                managementObject.InvokeMethod("SetGateways", newGateway, null);
                            }
                        }
                    }
                }
            }
        }
    }

    /// 
    /// Set's the DNS Server of the local machine
    /// 
    /// NIC address
    /// Comma seperated list of DNS server addresses
    /// Requires a reference to the System.Management namespace
    public void SetNameservers(string nic, string dnsServers)
    {
        using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
        {
            using (var networkConfigs = networkConfigMng.GetInstances())
            {
                foreach (var managementObject in networkConfigs.Cast().Where(objMO => (bool)objMO["IPEnabled"] && objMO["Caption"].Equals(nic)))
                {
                    using (var newDNS = managementObject.GetMethodParameters("SetDNSServerSearchOrder"))
                    {
                        newDNS["DNSServerSearchOrder"] = dnsServers.Split(',');
                        managementObject.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
                    }
                }
            }
        }
    }
}


注意:您必须向项目添加对System.Management的引用.

3> LukeSkywalke..:

我喜欢WMILinq解决方案.虽然不完全是您的问题的解决方案,但请在下面找到它的味道:

using (WmiContext context = new WmiContext(@"\\.")) {

  context.ManagementScope.Options.Impersonation = ImpersonationLevel.Impersonate;
  context.Log = Console.Out;

  var dnss = from nic in context.Source()
          where nic.IPEnabled
          select nic;

  var ips = from s in dnss.SelectMany(dns => dns.DNSServerSearchOrder)
          select IPAddress.Parse(s);
}  

http://www.codeplex.com/linq2wmi

推荐阅读
放ch养奶牛
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有