2013-03-21 5 views
6

次のように、私のアプリケーションをファイアウォールに追加するためにnetshを使用しました。ファイアウォールに追加する前に、アプリケーションがファイアウォールに追加されていないことを知る方法を教えてください。アプリケーションをファイアウォールに繰り返し追加したくないからです。アプリケーションがファイアウォールに追加されていないことを確認するにはどうすればよいですか?

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

この記事をチェックアウト:http://stackoverflow.com/questions/113755/programmatically-add-an-application-to-windows-firewall –

+0

@TheGreatCOどちらも、それは追加およびこれについてです、別の質問ですについては、 –

+0

を検出しています。通常、インストール中にこの操作を一度行います。この場合、ファイアウォールに追加するだけで、アンインストール時に削除するだけで確認する必要はありません。 –

答えて

1

TheGreatCO、ありがとうございます。私はそれを試して、それは働いた。

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; 
} 
関連する問題