1.配置程序权限为管理员权限运行,否则不会修改ip也不会报错
using System.Management;
static void Main(string[] args)
{
System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
{
Console.WriteLine("直接启动");
AllNetIp.SetNetworkAdapter("172.168.52.200", "255.255.255.0", "172.168.52.1");
}
else
{
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = Environment.CurrentDirectory;
startInfo.FileName = "XXXX.exe";
startInfo.Verb = "runas";
try
{
Console.WriteLine("重新已管理员身份启动");
System.Diagnostics.Process.Start(startInfo);
}
catch
{
return;
}
}
}
2.SetNetworkAdapter方法
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("不修改保护的地址");
continue;
}
Console.WriteLine("开始修改");
try
{
inPar = mo.GetMethodParameters("EnableStatic");
inPar["IPAddress"] = new string[] { ip };
inPar["SubnetMask"] = new string[] { mask };
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);
}
}
}
3.此时系统可能会弹出确认框

4.不想弹出该框的办法

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· 单线程的Redis速度为什么快?
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码