如何以编程方式在Windows操作系统中启用"网络发现"?

fxa*_*xam 4 c# windows upnp

我的项目使用UPnP协议打开端口.窗口在默认情况下禁用UPnP设备发现,需要打开网络发现网络和共享中心启用UPnP设备的发现.

有没有办法以编程方式执行此操作?

Mus*_*ici 11

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

netsh firewall set service type = upnp mode = mode
Run Code Online (Sandbox Code Playgroud)

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

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
  }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 谢谢,我也发现了"netsh advfirewall firewall"也很有用:http://support.microsoft.com/kb/947709 (2认同)
  • Fsham指出netsh防火墙已被淘汰,因为Fsham指出netsh advfirewall防火墙是替代品,因此您可以传递以下命令:“ netsh advfirewall防火墙设置规则组= \” Network Discovery \“ new enable = Yes” (2认同)