2013-03-21 39 views
6

Tôi đã sử dụng netsh để thêm ứng dụng của mình vào tường lửa như sau. Trước khi tôi thêm nó vào tường lửa, làm cách nào để biết rằng ứng dụng chưa được thêm vào tường lửa? bởi vì tôi không muốn thêm ứng dụng của tôi vào tường lửa nhiều lần.Làm cách nào để biết ứng dụng của tôi chưa được thêm vào tường lửa?

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

Check-out this post: http://stackoverflow.com/questions/113755/programmatically-add-an-application-to-windows-firewall –

+0

@TheGreatCO Cả hai đều là câu hỏi khác, đó là về việc thêm và điều này là về phát hiện –

+0

Thông thường bạn làm điều này một lần trong khi cài đặt - trong trường hợp đó bạn chỉ cần thêm nó vào tường lửa (và gỡ bỏ nó trong khi gỡ cài đặt) không cần phải kiểm tra. –

Trả lời

1

TheGreatCO, Cảm ơn bạn. Tôi đã thử nó và nó đã hoạt động.

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; 
} 
Các vấn đề liên quan