2013-03-21 7 views
6

Ich benutzte Netsh für meine Anwendung zu Firewall wie folgt hinzufügen. Wie kann ich wissen, dass die Anwendung der Firewall nicht hinzugefügt wurde, bevor ich sie zur Firewall hinzufüge? weil ich meine Anwendung nicht wiederholt zur Firewall hinzufügen möchte.Woher weiß ich, dass meine Anwendung nicht zur Firewall hinzugefügt wurde?

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

Schauen Sie sich diesen Beitrag: http://stackoverflow.com/questions/113755/programmatically-add-an-application-to-windows-firewall –

+0

@TheGreatCO Beide sind andere Frage, das heißt über das Hinzufügen und das ist über die Erkennung –

+0

In der Regel tun Sie dies einmal während der Installation - in diesem Fall Sie einfach hinzufügen, um die Firewall (und entfernen Sie es während der Deinstallation) keine Überprüfung erforderlich. –

Antwort

1

TheGreatCO, Danke. Ich habe es versucht und es hat funktioniert.

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