如何使用c#更改网络适配器的接口指标?
关于以下链接
https://stackoverflow.com/questions/5577406/enable-both-lan-intranet-and-usb-internet
有没有办法以编程方式使用ac#?
这是一篇代码项目文章,向您展示如何执行此操作:
http://www.codeproject.com/KB/IP/winnetstat.aspx
基本上,您使用IP Helper API和SetIpForwardEntry方法来完成此任务。
这篇文章将指导您如何实现它(附带代码):
虽然大约7年前就回答了这个问题,但我发现使用netsh.exe在C#中有一个非常简单的方法。
这仅在您以管理员身份运行程序时才有效。
命令是:
netsh.exe接口ipv4设置接口“myNICsName”metric = 20
要将度量设置为“自动”,只需将其设置为0.上限为9999,但如果使用更高的值,则只需将其设置为9999。
要以编程方式执行此操作,只需按以下方式使用Process.Start:
System.Diagnostics.Process p = new System.Diagnostics.Process { StartInfo = { FileName = "netsh.exe", Arguments = $"interface ipv4 set interface \"{nicName}\" metric={metric}", UseShellExecute = false, RedirectStandardOutput = true } }; bool started = p.Start(); if (started) { if (SpinWait.SpinUntil(() => p.HasExited, TimeSpan.FromSeconds(20))) { Log.Write($"Successfully set {nicName}'s metric to {metric}"); Log.Write($"Sleeping 2 seconds to allow metric change on {nicName} to take effect."); Thread.Sleep(2000); return true; } Log.Write($"Failed to set {nicName}'s metric to {metric}"); return false; }
上面的代码也进行了一些错误检查,以确保进程确实启动并放入一个短暂的延迟,以便度量标准更改有机会生效。 当我没有包含延迟时,我发现我的代码中存在一些问题。