我正在尝试制作一个简单的程序来改变C#中的IP参数。 我使用此代码:How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C# 执行它,并制定了我自己的方法:
public void changerip(string adresse, string NIC)
{
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if (objMO["Caption"].Equals(NIC))
{
try
{
if (adresse != "0")
{
ManagementBaseObject setIP;
ManagementBaseObject newIP =
objMC.GetMethodParameters("EnableStatic");
newIP["IPAddress"] = new string[] { "192.168." + adresse + ".50" };
newIP["SubnetMask"] = new string[] { "255.255.255.0" };
setIP = objMO.InvokeMethod("EnableStatic", newIP, null);
ManagementBaseObject setGateway;
ManagementBaseObject newGateway =
objMO.GetMethodParameters("SetGateways");
newGateway["DefaultIPGateway"] = new string[] { "192.168." + adresse + ".254" };
newGateway["GatewayCostMetric"] = new int[] { 1 };
setGateway = objMO.InvokeMethod("SetGateways", newGateway, null);
ManagementBaseObject newDNS =
objMO.GetMethodParameters("SetDNSServerSearchOrder");
newDNS["DNSServerSearchOrder"] = "192.168.1.24,192.168.1.2".Split(',');
ManagementBaseObject setDNS =
objMO.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
}
else
{
ManagementBaseObject newDNS = objMO.GetMethodParameters("SetDNSServerSearchOrder");
newDNS["DNSServerSearchOrder"] = null;
ManagementBaseObject enableDHCP = objMO.InvokeMethod("EnableDHCP", null, null);
ManagementBaseObject setDNS = objMO.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
//Save all Gateways into an array
string[] gateways = (string[])objMO["DefaultIPGateway"];
ManagementBaseObject newIP = objMO.GetMethodParameters("EnableStatic");
ManagementBaseObject newGate = objMO.GetMethodParameters("SetGateways");
//Set last value of the array(always the Gateway recived by DHCP) as the default Gateway
newGate["DefaultIPGateway"] = new string[] { gateways[gateways.Length - 1] };
newGate["GatewayCostMetric"] = new int[] { 1 };
}
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
}
}
它在Windows XP中运行良好,但在Windows 7(Starter或Pro)上不起作用。我没有任何异常上升,也没有来自操作系统的错误/安全消息。
有人知道发生了什么事吗?
答案 0 :(得分:4)
对我来说看起来像是凭据问题。您应该使用管理权限运行该程序。您只需右键单击exe并单击“以管理员身份运行”即可完成。