6

I used netsh for add my application to firewall as follows. Before I add it to the firewall, how to I know that the application has not been added to the firewall? because I do not want add my application to the firewall repeatedly.

ProcessStartInfo info = null;
try
{
    using (Process proc = new Process())
    {
        string productAssembly = new Uri(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase)).LocalPath + "\\" + this.ProductName + ".exe";
        string args = string.Format(CultureInfo.InvariantCulture, "advfirewall firewall add rule name=\"{0}\" dir=in action=allow program=\"{1}\" enable=yes", this.ProductName, productAssembly);
        info = new ProcessStartInfo("netsh", args);
        proc.StartInfo = info;
        proc.StartInfo.UseShellExecute = false;
        proc.StartInfo.CreateNoWindow = true;
        proc.StartInfo.RedirectStandardOutput = false;
        proc.Start();
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}
new bie
  • 2,745
  • 6
  • 24
  • 26
  • 1
    Check out this post: http://stackoverflow.com/questions/113755/programmatically-add-an-application-to-windows-firewall – Pete Garafano Mar 21 '13 at 18:10
  • @TheGreatCO Both are different question, that is about adding and this is about detecting – Mr. Alien Mar 21 '13 at 18:13
  • Typically you do this once during install--in which case you simply add it to the firewall (and remove it during uninstall) no need to check. – Peter Ritchie Mar 21 '13 at 18:13
  • @Mr.Alien those links should get you pretty far down the path of being able to query rules from the firewall, which is basically what you're asking to be able to do. – Pete Garafano Mar 21 '13 at 18:14
  • @TheGreatCO, Thank You. I've tried it and it worked :). I change **all** with **this.ProductName**. – new bie Mar 21 '13 at 18:15

1 Answers1

1

TheGreatCO, Thank You. I've tried it and it worked.

private bool isFirewallEnabled()
{
    ProcessStartInfo info = null;
    string result = string.Empty;
    try
    {
       using (Process proc = new Process())
       {
           string args = string.Format(CultureInfo.InvariantCulture, "advfirewall firewall show rule name=\"{0}\"", this.ProductName);
           info = new ProcessStartInfo("netsh", args);
           proc.StartInfo = info;
           proc.StartInfo.UseShellExecute = false;
           proc.StartInfo.CreateNoWindow = true;
           proc.StartInfo.RedirectStandardOutput = true;
           proc.Start();

           while ((result = proc.StandardOutput.ReadLine()) != null)
           {
               if (result.Replace(" ", String.Empty) == "Enabled:Yes")
               {
                   return true;
               }
            }
        }
    }
    catch (Exception ex)
    {
       MessageBox.Show(ex.Message);
    }
    return false;
}
new bie
  • 2,745
  • 6
  • 24
  • 26