Found a solution for this.
I've searched through a lot of sites, including codeplex, but couldn't find a good solution in managed code.
Most solutions were calling native code in protected locations, which can be blocked by UAC and some anti-virus programs. Some of them used COM components (hnetcfg.dll) and used kernal mode drivers.
But here's the simple way of doing things. Run netsh command. :laugh:
To open a port
netsh advfirewall firewall add rule name="rule name goes here" dir=in action=allow protocol=TCP localport=7777
Change name= and localport= to what ever you want.
To remove the rule
netsh advfirewall firewall delete rule name="rule name goes here" dir=in protocol=TCP localport=7777
NOTE: there is no action, because it doesn't make any sense. Actually protocol, dir and localport parameters are optional. But I recommend to always use them because this command deletes all results matching the criteria. So make sure you only delete the once you want tot delete.
Best Practices
Always run the delete command before adding a rule. It'll make sure you're not adding a duplicate rule. So you won't end-up with a zillion rules to allow the same port.
Happy Coding