If you've read Raymond Chen's blog long enough, then you know trying to change system stuff directly in Windows registry is discouraged, if not frowned upon. So when I kept hacking away at the registry trying to get some Windows Firewall exceptions for XP and Vista created, I decided to take a step back and see what Windows's API's are out there to do this.
Doing some Google searches doesn't reveal much (which is why I decided to blog this), except these two hidden gems Syslog daemon for Windows Eventlog, and Adding a port to the XP Firewall. Both of these gave me pointers in the right direction to create this gem:
1 private static void ExceptionToFirewall(bool add, string imageFileName, string name)
2 {
3 Type netFwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr");
4 INetFwMgr mgr = (INetFwMgr)Activator.CreateInstance(netFwMgrType);
5
6 INetFwProfile curProfile = mgr.LocalPolicy.CurrentProfile;
7 if (add)
8 {
9 Type NetFwAuthorizedApplicationType = Type.GetTypeFromProgID("HNetCfg.FwAuthorizedApplication", false);
10 INetFwAuthorizedApplication app = (INetFwAuthorizedApplication)Activator.CreateInstance(NetFwAuthorizedApplicationType);
11
12 app.Name = name;
13 app.ProcessImageFileName = imageFileName;
14 app.Enabled = true;
15 app.RemoteAddresses = "*";
16 app.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL;
17
18 curProfile.AuthorizedApplications.Add(app);
19 }
20 else
21 {
22 curProfile.AuthorizedApplications.Remove(imageFileName);
23 }
24 }
To use this, you'll need to add a reference to COM component HNetCfg.FwMgr (Guid "{304CE942-6E39-40D8-943A-B913C40C9CD4}", file path C:\windows\system32\hnetcfg.dll).
One note, don't use the IpVersion property of INetFwAuthorizedApplication, under Windows Vista it throws a NotImplimentedException.
del.icio.us Tags:
C#,
Windows,
Firewall