Updating existing firewall rule using API

前端 未结 3 1355
花落未央
花落未央 2021-02-06 02:02

I am able to pro grammatically add individual rules to the Windows Firewall (Server 2008 R2), however I am trying to avoid multiple rules per IP address, and would just like to

3条回答
  •  北恋
    北恋 (楼主)
    2021-02-06 02:26

    In addition to amdmax's answer (sorry I can't add a comment) I found that there is no simple method call to check to see if a rule exists so I came up with this to ensure that a rule is created whether it exists or not:

      INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(
          Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
    
      INetFwRule firewallRule = firewallPolicy.Rules.OfType().Where(x => x.Name == RULE_NAME).FirstOrDefault();
    
      if (firewallRule == null)
      {
        firewallRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
        firewallRule.Name = RULE_NAME;
        firewallPolicy.Rules.Add(firewallRule);
      }
    

提交回复
热议问题