A problem encountered in configuring IP settings using C# in Windows 7

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
I have one C# program which is used to change the IP settings in Windows. The program is built in Visual C# 2010 Express Edition. It functions properly in XP environment, that is, it changes the IP address, Gateway IP and subnet mask.
The program cannot achieve the same function in Windows 7. I have re-compiled it in Windows 7 using the same compiler. The newly built program does not return any error as the last message "Update IP address" is observed. However, the IP
settings do not change. Is there any any work required in Windows 7? The program is shown as below.
using System;<br/>
using System.Collections.Generic;<br/>
using System.Linq;<br/>
using System.Text;<br/>
// for ManagementClass, ManagementObjectCollection<br/>
using System.Management;
namespace GetMyIP7<br/>
{<br/>
class Program<br/>
{<br/>
const string IntraLAN = "Intel(R) PRO/100 VE Network Connection";<br/>
static void Main(string[] args)<br/>
{<br/>
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
<br/>
ManagementObjectCollection objMOC = objMC.GetInstances();<br/>
ManagementObject ReqMO = null;<br/>
foreach (ManagementObject objMO in objMOC)<br/>
{<br/>
// check whether objMOs caption contains IntraLAN<br/>
if (objMO["Caption"].ToString().Contains(IntraLAN))<br/>
{<br/>
ReqMO = objMO;<br/>
break;<br/>
}<br/>
}<br/>
// return if not found<br/>
if (ReqMO == null) return;<br/>
Console.WriteLine("Found the management object with the caption containing {0}", IntraLAN);<br/>
// return if not IP enabled<br/>
if (!((bool)ReqMO["ipEnabled"])) return;<br/>
Console.WriteLine("The object is IP enabled");<br/>
// get IP address if IP enabled<br/>
int n = 0;<br/>
string[] ipAddrs = (string[])ReqMO["IPAddress"];<br/>
foreach (string ip in ipAddrs)<br/>
{<br/>
Console.WriteLine("IP address {0}: {1}", n++, ip);<br/>
}
// try to set IP address<br/>
try<br/>
{<br/>
Console.WriteLine("Try to set a new IP address");<br/>
ManagementBaseObject objNewIP = null;<br/>
ManagementBaseObject objSetIP = null;<br/>
ManagementBaseObject objNewGate = null;<br/>
objNewIP = ReqMO.GetMethodParameters("EnableStatic");<br/>
objNewGate = ReqMO.GetMethodParameters("SetGateways");
string gateIP = "192.167.0.1";<br/>
string ip = "192.167.0.123";<br/>
string smask = "255.255.255.0";<br/>
objNewGate["DefaultIPGateway"] = new string[] { gateIP };<br/>
objNewGate["GatewayCostMetric"] = new int[] { 1 };
objNewIP["IPAddress"] = new string[] { ip };<br/>
objNewIP["SubnetMask"] = new string[] { smask };<br/>

<br/>
objSetIP=ReqMO.InvokeMethod("EnableStatic", objNewIP, null);<br/>
objSetIP = ReqMO.InvokeMethod("setGateways", objNewGate, null);
Console.WriteLine("Update IP address");
}<br/>
catch (Exception e)<br/>
{<br/>
Console.WriteLine(e.ToString());<br/>
}
Console.ReadLine();
}<br/>
}<br/>
}

View the full article
 
Back
Top