Search code examples
c#.netwindows-firewall-api

Turn Firewall on and off of using C#


I have written a C# program that uses command line arguments to turn the firewall on and off.

Process proc = new Process();
string top = "netsh.exe";
proc.StartInfo.Arguments = "**Advfirewall set allprofiles state on**";
proc.StartInfo.FileName = top;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
proc.WaitForExit();
// MessageBox.Show("Disable");
button1.Text = "Set On";
status = false;

I also run the application with admin permission. The application automatically runs with admin permissions but does not set firewall status on or off.

When I run the same command in cmd(netsh) the firewall is turned on or off.

Does anyone know why this is not working?


Solution

  • Running the same code but removing the ** seems to work. i.e. you need to change this:

    proc.StartInfo.Arguments = "**Advfirewall set allprofiles state on**";
    

    to this:

    proc.StartInfo.Arguments = "Advfirewall set allprofiles state on";
    

    Note that you should be running the app that starts the process as an administrator and to start the process as admin you can also use:

    proc.StartInfo.Verb = "runas";