Using Windows Firewall NetFwMgr from .NET application
There are two ways to use WF com object from .Net code:
- Create the NetFwMgr dynamically using class ID and Activator.CreateInstance()
- Use .Net interop assembly.
I prefer the second method. It is easier to use and make me feel better.
The first method involves these two calls:
- NetFwMgrType = Type.GetTypeFromCLSID(new Guid("{304CE942-6E39-40D8-943A-B913C40C9CD4}"));
- //Create an instance of the object
- NetFwMgrObject = Activator.CreateInstance(NetFwMgrType);
The second method looks like this:
1. using NetFwPublicTypeLib;
2. //Get the FW Manager
3. NetFwMgr mgr = new NetFwMgrClass();
4. //create new application object
5. NetFwAuthorizedApplication app = new NetFwAuthorizedApplicationClass();
6. app.Name = "CalcServiceHost";
7. app.Enabled = true;
8. app.ProcessImageFileName = @"C:\...\CalcServerHost.exe";
9. app.RemoteAddresses = "192.168.0.142";
10. app.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_LOCAL_SUBNET;
11. //add application
12. mgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(app);
The only problem with the second method is that we have to add a reference to a type library which does not exist. Here comes the trick:
Use the MIDL compiler on the idl file of the NetFwMgr that resides in the include directory that you have installed with the XP SP2 Platform SDK. This will create the type library that you can refer to (using tlbimp.exe or via visual studio).
>cd C:\Program Files\Microsoft Platform SDK for Windows XP SP2\Include\
>midl netfw.idl
Probably Microsoft will give us a PIA or something else to use the WF APIs from .NET app.
You may use the same MIDL trick to use the new attachment services as well.
For more Windows XP SP2 Links, refer to this article.