代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
namespace 设置IP地址
{
class Program
{
static void SetNetworkAdapter()
{
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;
Console.Out.WriteLine("do settings....");
//设置ip地址和子网掩码
inPar = mo.GetMethodParameters( "EnableStatic" );
inPar["IPAddress"] = new string[] { "10.22.21.111","192.168.10.9" };
inPar["SubnetMask"] = new string[] { "255.255.255.0","255.255.255.0" };
outPar = mo.InvokeMethod( "EnableStatic", inPar, null );
//设置网关地址
inPar = mo.GetMethodParameters("SetGateways");
inPar["DefaultIPGateway"] = new string[] { "10.22.21.1","192.168.10.1"};
outPar = mo.InvokeMethod( "SetGateways", inPar, null );
//设置DNS
inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
inPar["DNSServerSearchOrder"] = new string[] {"179.32.42.4","179.32.42.5"};
outPar = mo.InvokeMethod( "SetDNSServerSearchOrder" ,inPar,null);
break;
}
}
static void Main(string[] args)
{
SetNetworkAdapter();
Console.Out.WriteLine("done");
}
}
}
代码其实没有问题,上述代码在有的电脑上好用,有的电脑却不行。原因是:不行的电脑执行的时候权限不够导致的。
解决方法很简单:
在exe上点右键,以管理员身份运行。