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

1 回答 1

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;
}
于 2013-03-21T18:48:06.250 回答