I want to use Win32_IP4RouteTable to add route table
code:
ManagementClass wmiclass = new ManagementClass("Win32_IP4RouteTable");
ManagementObject route = wmiclass.CreateInstance();
route["Destination"] = "145.63.20.102";
route["NextHop"] = "172.16.213.2";
route["Mask"] = "255.255.255.255";
route["Metric1"] = 20;
route.Put();//or route.Put(new PutOptions() { Type =
PutType.UpdateOrCreate });
I get an Exception on Put() method:
`System.Management.Management:Invalid parameter`
How could I use Put method to create a new Item
答案 0 :(得分:0)
[DllImport("Iphlpapi.dll")]
[return: MarshalAs(UnmanagedType.U4)]
public static extern int CreateIpForwardEntry(ref MIB_IPFORWARDROW pRoute);
public static int createIpForwardEntry(UInt32 destIPAddress, UInt32 destMask, UInt32 nextHopIPAddress, UInt32 ifIndex, int metric)
{
MIB_IPFORWARDROW mifr = new MIB_IPFORWARDROW();
mifr.dwForwardDest = destIPAddress;
mifr.dwForwardMask = destMask;
mifr.dwForwardNextHop = nextHopIPAddress;
mifr.dwForwardIfIndex = ifIndex;
mifr.dwForwardPolicy = Convert.ToUInt32(0);
mifr.dwForwardType = Convert.ToUInt32(3);
mifr.dwForwardProto = Convert.ToUInt32(3);
mifr.dwForwardAge = Convert.ToUInt32(0);
mifr.dwForwardNextHopAS = Convert.ToUInt32(0);
mifr.dwForwardMetric1 = metric;
mifr.dwForwardMetric2 = -1;
mifr.dwForwardMetric3 = -1;
mifr.dwForwardMetric4 = -1;
mifr.dwForwardMetric5 = -1;
return CreateIpForwardEntry(ref mifr);
}
`
答案 1 :(得分:0)
您可以使用ORMi库。对于WMI来说,它是一个轻量级的ORM。
1)定义你的班级:
[WMIClass("Win32_IP4RouteTable")]
public class RouteTable
{
public string Destination{ get; set; }
public string NextHop{ get; set; }
public string Mask{ get; set; }
public string Metric1{ get; set; }
}
注意:似乎有一些属性可能需要,因为你得到'无效参数'。如果是这种情况,那么只需将所需的clases添加到RouteTable
类。
2)使用库:
WMIHelper helper = new WMIHelper("root\\CimV2");
RouteTable route = new RouteTable
{
Destination = "145.63.20.102",
NextHop = "172.16.213.2",
Mask = "255.255.255.255",
Metric1 = "20"
};
helper.AddInstance(route);
就是这样。