Create firewall rule to open port per application programmatically in c#

前端 未结 2 959
耶瑟儿~
耶瑟儿~ 2021-02-09 19:56

I need to open specific port for my application.

I have tried using INetFwAuthorizedApplication rule per application for all ports.

fwMgr.Lo         


        
2条回答
  •  北恋
    北恋 (楼主)
    2021-02-09 20:07

    You could also just use PowerShell.

    using System.Management.Automation;
    ...
    private void OpenPort(int port)
    {
        var powershell = PowerShell.Create();
        var psCommand = $"New-NetFirewallRule -DisplayName \"\" -Direction Inbound -LocalPort {port} -Protocol TCP -Action Allow";
        powershell.Commands.AddScript(psCommand);
        powershell.Invoke();
    }
    

提交回复
热议问题