Created
February 11, 2019 20:32
-
-
Save jbe2277/53ebc48181bce987f87daf81d50c71b2 to your computer and use it in GitHub Desktop.
Windows Firewall: Read and Add Rule
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
internal class WindowsFirewallService | |
{ | |
public static void AddRule(string ruleName, string udpPort) | |
{ | |
var policy = CreatePolicy(); | |
var rule = CreateRule(); | |
rule.Name = ruleName; | |
rule.Enabled = true; | |
rule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW; | |
rule.Profiles = (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_ALL; | |
rule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP; | |
rule.LocalPorts = udpPort; | |
policy.Rules.Add(rule); | |
} | |
public static bool GetIsRuleActiveAsync(string ruleName) | |
{ | |
var policy = CreatePolicy(); | |
var rules = policy.Rules.Cast<INetFwRule2>().Where(x => x.Direction == NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN && x.Name == ruleName); | |
var profiles = rules.Select(x => (NET_FW_PROFILE_TYPE2_)x.Profiles).ToArray(); | |
return profiles.Any(x => x.HasFlag(NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_DOMAIN)) | |
&& profiles.Any(x => x.HasFlag(NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE)) | |
&& profiles.Any(x => x.HasFlag(NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC)); | |
} | |
private static INetFwPolicy2 CreatePolicy() => (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2")); | |
private static INetFwRule2 CreateRule() => (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment