如何在c#中禁用/启用网络连接

23 c# networking lan

基本上我正在运行一些性能测试,并且不希望外部网络成为阻力因素.我正在研究禁用网络局域网的方法.以编程方式执行此操作的有效方法是什么?我对c#感兴趣.如果有人有一个代码片段,可以驱动点回家很酷.

Mel*_*vyn 28

在搜索相同的东西时找到这个帖子,所以,这里是答案:)

我在C#中测试的最佳方法是使用WMI.

http://www.codeproject.com/KB/cs/EverythingInWmi02.aspx

msdn上的Win32_NetworkAdapter

C#Snippet :(必须在解决方案中引用System.Management,并使用声明)

SelectQuery wmiQuery = new SelectQuery("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionId != NULL");
ManagementObjectSearcher searchProcedure = new ManagementObjectSearcher(wmiQuery);
foreach (ManagementObject item in searchProcedure.Get())
{
    if (((string)item["NetConnectionId"]) == "Local Network Connection")
    {
       item.InvokeMethod("Disable", null);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,我必须以管理员身份运行它(当我将它作为peon运行时,InvokeMethod()没有返回错误). (6认同)

小智 15

使用netsh命令,您可以启用和禁用"本地连接"

  interfaceName is “Local Area Connection”.

  static void Enable(string interfaceName)
    {
     System.Diagnostics.ProcessStartInfo psi =
            new System.Diagnostics.ProcessStartInfo("netsh", "interface set interface \"" + interfaceName + "\" enable");
        System.Diagnostics.Process p = new System.Diagnostics.Process();
        p.StartInfo = psi;
        p.Start();
    }

    static void Disable(string interfaceName)
    {
        System.Diagnostics.ProcessStartInfo psi =
            new System.Diagnostics.ProcessStartInfo("netsh", "interface set interface \"" + interfaceName + "\" disable");
        System.Diagnostics.Process p = new System.Diagnostics.Process();
        p.StartInfo = psi;
        p.Start();
    }
Run Code Online (Sandbox Code Playgroud)


小智 5

如果您正在寻找一种非常简单的方法来做到这一点,请访问:

    System.Diagnostics.Process.Start("ipconfig", "/release"); //For disabling internet
    System.Diagnostics.Process.Start("ipconfig", "/renew"); //For enabling internet
Run Code Online (Sandbox Code Playgroud)

确保以管理员身份运行。我希望你觉得这有帮助!