【问题标题】:How to programmatically turn on "Network Discovery" in Windows OS?如何以编程方式在 Windows 操作系统中打开“网络发现”?
【发布时间】:2011-11-30 06:51:04
【问题描述】:

我的项目使用 UPnP 协议打开端口。 Windows 默认禁用 UPnP 设备发现,需要在网络和共享中心中开启网络发现才能启用 UPnP 设备发现。

有没有办法以编程方式做到这一点?

【问题讨论】:

    标签: c# windows upnp


    【解决方案1】:

    您可以使用 cmd 命令来启用网络发现

    netsh firewall set service type = upnp mode = mode
    

    然后将该命令作为参数提供给代码

    public void ExecuteCommandSync(object command)
    {
      try
      {
        // create the ProcessStartInfo using "cmd" as the program to be run,
        // and "/c " as the parameters.
        // Incidentally, /c tells cmd that we want it to execute the command that follows,
        // and then exit.
        System.Diagnostics.ProcessStartInfo procStartInfo =
          new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
    
        // The following commands are needed to redirect the standard output.
        // This means that it will be redirected to the Process.StandardOutput StreamReader.
        procStartInfo.RedirectStandardOutput = true;
        procStartInfo.UseShellExecute = false;
        // Do not create the black window.
        procStartInfo.CreateNoWindow = true;
        // Now we create a process, assign its ProcessStartInfo and start it
        System.Diagnostics.Process proc = new System.Diagnostics.Process();
        proc.StartInfo = procStartInfo;
        proc.Start();
        // Get the output into a string
        string result = proc.StandardOutput.ReadToEnd();
        // Display the command output.
        Console.WriteLine(result);
      }
      catch (Exception objException)
      {
        // Log the exception
      }
    }
    

    如果该命令不起作用,请根据您的系统查找另一个启用网络发现的命令。

    【讨论】:

    • 谢谢,我还发现“netsh advfirewall firewall”也很有用:support.microsoft.com/kb/947709
    • netsh 防火墙已弃用,正如 Fxam 指出的,netsh advfirewall 防火墙是替代品,因此您可以传递如下命令:“netsh advfirewall firewall set rule group=\"Network Discovery\" new enable=Yes"
    猜你喜欢
    • 2011-06-29
    • 2016-10-08
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    • 2011-06-29
    • 1970-01-01
    • 2010-09-18
    相关资源
    最近更新 更多