如何在Windows操作系统中以编程方式打开“网络发现”?

4

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

是否有通过编程实现此功能的方法?

1个回答

11

您可以使用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
  }
}

如果该命令无效,根据您的系统找到另一个启用网络发现的命令。


2
谢谢,我还发现了“netsh advfirewall firewall”,这也很有用:http://support.microsoft.com/kb/947709 - fxam
3
如Fxam所指出,netsh firewall已经过时,netsh advfirewall firewall是其替代品,因此您可以传递这样的命令:"netsh advfirewall firewall set rule group="网络发现" new enable=Yes" - Steve Byrne

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接