1.配置程序權(quán)限為管理員權(quán)限運(yùn)行,否則不會(huì)修改ip也不會(huì)報(bào)錯(cuò)
using System.Management;//需要引用的包
static void Main(string[] args)
{
//獲得當(dāng)前登錄的Windows用戶標(biāo)示
System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
//判斷當(dāng)前登錄用戶是否為管理員
if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
{
//如果是管理員篮奄,則直接運(yùn)行
Console.WriteLine("直接啟動(dòng)");
AllNetIp.SetNetworkAdapter("172.168.52.200", "255.255.255.0", "172.168.52.1");//AllNetIp 是類名稱
}
else
{
//創(chuàng)建啟動(dòng)對象
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = Environment.CurrentDirectory;
startInfo.FileName = "XXXX.exe";// Application.ExecutablePath;
//設(shè)置啟動(dòng)動(dòng)作,確保以管理員身份運(yùn)行
startInfo.Verb = "runas";
try
{
Console.WriteLine("重新已管理員身份啟動(dòng)");
System.Diagnostics.Process.Start(startInfo);
}
catch
{
return;
}
}
}
2.SetNetworkAdapter方法
/// <summary>
/// 修改本機(jī)IP
/// </summary>
public static void SetNetworkAdapter(string ip,string mask,string host)
{
ManagementBaseObject inPar = null;
ManagementBaseObject outPar = null;
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
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("不修改保護(hù)的地址");
continue;
}
Console.WriteLine("開始修改");
try
{
//設(shè)置ip地址和子網(wǎng)掩碼
inPar = mo.GetMethodParameters("EnableStatic");
inPar["IPAddress"] = new string[] { ip };
inPar["SubnetMask"] = new string[] { mask };//"255.255.255.0"
outPar = mo.InvokeMethod("EnableStatic", inPar, null);
//設(shè)置網(wǎng)關(guān)地址
inPar = mo.GetMethodParameters("SetGateways");
inPar["DefaultIPGateway"] = new string[] { host };
outPar = mo.InvokeMethod("SetGateways", inPar, null);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
//設(shè)置DNS
//inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
//inPar["DNSServerSearchOrder"] = new string[] { "179.32.42.4", "179.32.42.5" };
//outPar = mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);
//break;
}
}
3.此時(shí)系統(tǒng)可能會(huì)彈出確認(rèn)框
4.不想彈出該框的辦法