2013-03-21 11 views
6

Ho usato netsh per aggiungere la mia applicazione al firewall come segue. Prima di aggiungerlo al firewall, come faccio a sapere se l'applicazione non è stata aggiunta al firewall? perché non desidero aggiungere più volte la mia applicazione al firewall.Come faccio a sapere se la mia applicazione non è stata aggiunta al firewall?

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); 
} 
+1

controllare questo post: http://stackoverflow.com/questions/113755/programmatically-add-an-application-to-windows-firewall –

+0

@TheGreatCO Entrambi sono questione diversa, che è di aggiungere, e questo si tratta di rilevare –

+0

In genere lo si fa una volta durante l'installazione - nel qual caso è sufficiente aggiungerlo al firewall (e rimuoverlo durante la disinstallazione) senza bisogno di controllare. –

risposta

1

TheGreatCO, grazie. L'ho provato e ha funzionato.

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; 
}