调用system.management时,下文代码中第三行运行会报错,报错内容为:
System.Runtime.InteropServices.MarshalDirectiveException:“Cannot marshal 'parameter #3': Cannot marshal a string by-value with the [Out] attribute.”
原代码:
ManagementBaseObject inPar = null;
ManagementBaseObject outPar = null;
//下面这一行代码报错
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConf**iguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if (!(bool)mo["IPEnabled"])
continue;
string[] addresses = (string[])mo["IPAddress"];
if (addresses[0].Contains("xxx.xxx.xxx.xxx"))
{
Console.WriteLine("不修改保护的地址");
continue;
}
Console.WriteLine("开始修改");
try
{
//设置ip地址和子网掩码
inPar = mo.GetMethodParameters("EnableStatic");
inPar["IPAddress"] = new string[] { ip };
inPar["SubnetMask"] = new string[] { mask };//"255.255.255.0"
outPar = mo.InvokeMethod("EnableStatic", inPar, null);
//设置网关地址
inPar = mo.GetMethodParameters("SetGateways");
inPar["DefaultIPGateway"] = new string[] { host };
outPar = mo.InvokeMethod("SetGateways", inPar, null);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}