boonwin
boonwin

Reputation: 69

Enable and Disable Windows Firewall Rule with WindowsFirewallHelper c#

Hi im using the WindowsFirewallHelper Lib from here: WindowsFirewallHelper Git

First I Create a Rule

 IRule rule = FirewallManager.Instance.CreateApplicationRule(
            FirewallManager.Instance.GetProfile().Type,
            ruleName,
            FirewallAction.Block,
            @"Path\App.exe"
            );
            rule.Direction = FirewallDirection.Outbound;
            FirewallManager.Instance.Rules.Add(rule);

After that I would like to make a Connect and Disconect Method which enables or disables this rule, but I cant find any Method for it within the lib, does anybody know how to do that? There is only the "rule.isEnabled" field which tells if it is enabled or not.

Upvotes: 3

Views: 1549

Answers (2)

DSLTIP
DSLTIP

Reputation: 1

You can do it this way:
var myRule = FirewallManager.Instance.Rules.SingleOrDefault(r => r.Name == "rulename"); if (myRule != null)myRule.IsEnable = false;

Upvotes: 0

boonwin
boonwin

Reputation: 69

Since I couldnt make it happen with the Lib: I did the following for enable and disable methods:

I created a CMD Method

       private static void RunCMD(string argument)
    {
        Process process = new Process();
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.FileName = @"C:\Windows\System32\cmd.exe";       
        startInfo.Arguments = argument;
        process.StartInfo = startInfo;
        process.Start();
    }

Then I added both Other Methods:

   public static void Disconnect()
    {

        RunCMD(@"/C netsh advfirewall firewall set rule name=""RULENAME"" new enable=no");

    }


    public static void Connect()
    {
        RunCMD(@"/C netsh advfirewall firewall set rule name=""RULENAME"" new enable=yes");
    }

Upvotes: 3

Related Questions