c# - 我怎么知道我的应用程序没有被添加到防火墙?

标签 c# winforms firewall netsh

我使用 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);
}

最佳答案

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

关于c# - 我怎么知道我的应用程序没有被添加到防火墙?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15554979/

相关文章:

c# - 操作和比较字符串的最佳方法

c# - 将 XML 解析为 Treeview 列表

.net - .NET Winform-多行 ListView (请参见屏幕截图)

firewall - 将 Fabric 和 Crashlytics IP 列入白名单

c# - 在键值对中查找已经存在的值

java - Java 是否具有与 C# 的元组等效的变量类型?

c# - 如何在 WinForms 和 C# 中创建下拉菜单

kubernetes - 如何添加防火墙规则以允许通过 kubernetes 中的虚拟 ip 访问节点端口

docker - 如何在Kubernetes下使用Fail2ban?

c# - .Net Core Async Await - 未按预期运行