以c#编程方式设置网络配置
本文关键字:网络 配置 设置 方式 编程 | 更新日期: 2023-09-27 18:10:28
我想保存我的网络适配器配置,然后在另一台计算机上恢复它。我使用WMI来获取我的网络配置,并将其保存到。txt文件中:
using (TextWriter tw = new StreamWriter(@"D:''NetworkConfiguration.txt"))
{
if (tw != null)
{
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if (!(bool)objMO["ipEnabled"])
continue;
string[] ipaddresses = (string[])objMO["IPAddress"];
string[] subnets = (string[])objMO["IPSubnet"];
string[] gateways = (string[])objMO["DefaultIPGateway"];
tw.WriteLine("IpAdresses");
foreach (string sIP in ipaddresses)
tw.WriteLine(sIP);
tw.WriteLine("IpSubnets");
foreach (string sNet in subnets)
tw.WriteLine(sNet);
tw.WriteLine("Gateways");
foreach (string sGate in gateways)
tw.WriteLine(sGate);
// close the stream
tw.Close();
}
}
}
然后,当我想在另一台计算机上设置tcp/ip设置时,我读取文件的信息:
using (TextReader tr = new StreamReader(@"D:''NetworkConfiguration.txt"))
{
List<string> ipAddrr = new List<string>();
List<string> ipSubnet = new List<string>();
List<string> Gateway = new List<string>();
string line = tr.ReadLine();
while (line != null)
{
if (line.Equals("IpAdresses"))
{
ipAddrr.Add(tr.ReadLine());
ipAddrr.Add(tr.ReadLine());
}
if (line.Equals("IpSubnets"))
{
ipSubnet.Add(tr.ReadLine());
ipSubnet.Add(tr.ReadLine());
}
if (line.Equals("Gateways"))
{
Gateway.Add(tr.ReadLine());
}
line = tr.ReadLine();
}
setIP(ipAddrr.ToArray(), ipSubnet.ToArray(), Gateway.ToArray());
}
并设置新设置:
public void setIP(string[] IPAddress, string[] SubnetMask, string[] Gateway)
{
ManagementClass objMC = new ManagementClass(
"Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if (!(bool)objMO["IPEnabled"])
continue;
try
{
ManagementBaseObject objNewIP = null;
ManagementBaseObject objSetIP = null;
ManagementBaseObject objNewGate = null;
objNewIP = objMO.GetMethodParameters("EnableStatic");
objNewGate = objMO.GetMethodParameters("SetGateways");
//Set DefaultGateway
objNewGate["DefaultIPGateway"] = Gateway ;
objNewGate["GatewayCostMetric"] = new int[] { 1 };
//Set IPAddress and Subnet Mask
objNewIP["IPAddress"] = IPAddress;
objNewIP["SubnetMask"] = SubnetMask;
objSetIP = objMO.InvokeMethod("EnableStatic", objNewIP, null);
objSetIP = objMO.InvokeMethod("SetGateways", objNewGate, null);
MessageBox.Show(
"Updated IPAddress, SubnetMask and Default Gateway!");
}
catch (Exception ex)
{
MessageBox.Show("Unable to Set IP : " + ex.Message);
}
}
}
,但问题是,当我检查我的tcp/ip配置,它永远不会改变.....我不知道怎么让它工作....
看一下这个问题-不同的方法,但应该没问题。