来源:
原名:Configuring TCP/IP Settings using WMI and C#
用C#设置IP的一种方法
//here is the code to configure TCP/IP Settings using WMI
public static void setIP(string IPAddress,string SubnetMask, string Gateway)
{
ManagementClass objMC = new ManagementClass(
"Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach(ManagementObject objMO in objMOC)
{
if (!(bool) objMO["IPEnabled"])
continue;
try
{
ManagementBaseObject objNewIP = null;
ManagementBaseObject objSetIP = null;
ManagementBaseObject objNewGate = null;
objNewIP = objMO.GetMethodParameters("EnableStatic");
objNewGate = objMO.GetMethodParameters("SetGateways");
//Set DefaultGateway
objNewGate["DefaultIPGateway"] = new string[] {Gateway};
objNewGate["GatewayCostMetric"] = new int[] {1};
//Set IPAddress and Subnet Mask
objNewIP["IPAddress"] = new string[] {IPAddress};
objNewIP["SubnetMask"] = new string[] {SubnetMask};
objSetIP = objMO.InvokeMethod("EnableStatic",objNewIP,null);
objSetIP = objMO.InvokeMethod("SetGateways",objNewGate,null);
Console.WriteLine(
"Updated IPAddress, SubnetMask and Default Gateway!");
}
catch(Exception ex)
{
MessageBox.Show("Unable to Set IP : " + ex.Message); }
}
}
已经验证代码可用.
验证环境:win2000专业版
编译信息:
Microsoft (R) Visual C# 2005 编译器 版本 8.00.50727.42
用于 Microsoft (R) Windows (R) 2005 Framework 版本 2.0.50727
版权所有 (C) Microsoft Corporation 2001-2005。保留所有权利。
阅读(1509) | 评论(0) | 转发(0) |