Question add firewall rule in C#?

monte carlo

New member
Joined
Jan 15, 2022
Messages
1
Programming Experience
Beginner
I want to convert this batch code into C#. Advance thanks.

C#:
::Variables
set RULE_NAME=SmartPLS
set PROGRAM=C:\Program Files\SmartPLS 3\SmartPLS.exe
netsh advfirewall firewall add rule name="%RULE_NAME%" dir=in action=block profile=any program="%PROGRAM%"
netsh advfirewall firewall add rule name="%RULE_NAME%" dir=out action=block profile=any program="%PROGRAM%"
 
I want to convert this batch code into C#. Advance thanks.

C#:
::Variables
set RULE_NAME=SmartPLS
set PROGRAM=C:\Program Files\SmartPLS 3\SmartPLS.exe
netsh advfirewall firewall add rule name="%RULE_NAME%" dir=in action=block profile=any program="%PROGRAM%"
netsh advfirewall firewall add rule name="%RULE_NAME%" dir=out action=block profile=any program="%PROGRAM%"
To literally translate your batch code to C# you could use Process.Start().
Although using a NuGet package, as JohnH suggested, is probably a smarter and more elegant solution.

C#:
using System.Diagnostics;
using System.IO;
using System;

static string rule_name =  "SmartPLS";
static string program   = @"C:\Program Files\SmartPLS 3\SmartPLS.exe";
static string cmd       = @"C:\WINDOWS\SYSTEM32\netsh.exe";
static string parms    = "advfirewall firewall add rule name=\"{0}\" dir={1} action=block profile=any program=\"{2}\"";

static void addRule (string dir)
{
    System.Diagnostics.Process.Start(cmd, String.Format(parms, rule_name, dir, program));
}

addRule("in ");
addRule("out");
 
Back
Top Bottom