You can use linq when initializing your firewall rules to be selective/specific.
For multiple firewall rules with the same name:
INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
List<INetFwRule> firewallRules = firewallPolicy.Rules.OfType<INetFwRule>().Where(x => x.Name.Contains(fwRuleName)).ToList();
foreach (INetFwRule rule in firewallRules)
{
firewallPolicy.Rules.Remove(rule.Name);
}
For a single firewall rule:
INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
INetFwRule firewallRule = firewallPolicy.Rules.OfType<INetFwRule>().Where(x => x.Name == fwRuleName).FirstOrDefault();
firewallPolicy.Rules.Remove(firewallRule.Name);
However, if you know the firewall rule name already, you might also just be able to do this (untested, but without the Where
clause):
INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
firewallPolicy.Rules.Remove(fwRuleName);
The point though was to show the linq syntax and the flexibility of being able to search specific names, patterns, etc. with it.