C# 在Windows 7上设置计算机IP

C# 在Windows 7上设置计算机IP,c#,wmi,C#,Wmi,我正在编写一段代码,使用自定义DHCP协议获取ip。然后,代码需要将其中一台计算机NIC设置为该ip 下面是我的代码 private void SetIp(IPAddress ipAddress, IPAddress subnetMask, IPAddress gatewayAddress) { try { ManagementBaseObject objNewIP = null;

我正在编写一段代码,使用自定义DHCP协议获取ip。然后,代码需要将其中一台计算机NIC设置为该ip

下面是我的代码

    private void SetIp(IPAddress ipAddress, IPAddress subnetMask, IPAddress gatewayAddress)
    {
            try
            {
                ManagementBaseObject objNewIP = null;
                ManagementBaseObject objSetIP = null;
                ManagementBaseObject objNewGate = null;


                objNewIP = networkInterface.GetMethodParameters("EnableStatic");
                objNewGate = networkInterface.GetMethodParameters("SetGateways");



                //Set DefaultGateway
                objNewGate["DefaultIPGateway"] = new string[] { gatewayAddress.ToString() };
                objNewGate["GatewayCostMetric"] = new int[] { 1 };


                //Set IPAddress and Subnet Mask
                objNewIP["IPAddress"] = new string[] { ipAddress.ToString() };
                objNewIP["SubnetMask"] = new string[] { subnetMask.ToString() };

                objSetIP = networkInterface.InvokeMethod("EnableStatic", objNewIP, null);
                objSetIP = networkInterface.InvokeMethod("SetGateways", objNewGate, null);



                Console.WriteLine(
                   "Updated IPAddress, SubnetMask and Default Gateway!");



            }
            catch (Exception ex)
            {
            }

        // throw new System.NotImplementedException();
    }
我在EnableStatic通话中不断收到2147749891。这篇文章建议我需要在我所做的机器上拥有管理员权限

microsoft页面建议我需要获得一个写锁,它需要com代码,我宁愿避免使用com代码

有没有更好的方法来实现这一点,可能是使用netsh,也可能是不需要管理员权限的方式?我只需要设置NIC的mac地址和详细信息


谢谢

我在调用EnableStatic时遇到了相同的错误

将正在运行的用户提升为管理员运行解决了我的问题,这似乎很正常:只有管理员可以更改NIC参数

我还没有确定为什么具有管理员权限的用户不能运行相同的代码,可能是UAC问题,调查正在进行中

对于microsoft页面,未启用的写锁定为2147786788。 不是2147749891