Checking Windows Firewall Using C#
CodeBecause I’ve had such a hard time finding a decent example of manipulating the Windows Firewall using C# online, I’ve decided to paste a small portion of code that might help others in such matters. Below is an example of how to determine the Windows Firewall state using C# and the modern INetFwPolicy2 interface, rather than the older INetFwMgr examples that seem to be around.
INetFwPolicy2 firewall = null;
Type progID = null;
progID = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
firewall = (INetFwPolicy2)Activator.CreateInstance(progID);
int currentProfiles = firewall.CurrentProfileTypes;
if (firewall.FirewallEnabled[(NET_FW_PROFILE_TYPE2_)currentProfiles])
{
Console.WriteLine("Firewall is enabled.\n");
}
else
{
Console.WriteLine("Firewall is not enabled.\n");
}