雷达智富

首页 > 内容 > 程序笔记 > 正文

程序笔记

C#给应用程序添加防火墙规则配置

2024-08-07 24

问题描述

有网络访问要求的应用程序,比如程序监听某一网络端口,如果Windows系统有防火墙限制,则可能程序无法收到网络请求或者UDP网络包,此时要么关闭掉防火墙(不推荐),要么给程序添加到信任列表,或者给程序添加防火墙规则。虽然可以手动做这些配置,但应用分发后,不方便让客户自己去做这个操作,所以使用程序来配置就变为尤为必要了。下面将介绍在C#中如何添加防火墙规则。

解决办法

添加引用NetFwTypeLib.dll

这个动态库在系统目录中:
64位程序引用这个路径:C:\Windows\System32\FirewallAPI.dll
32位程序引用这个路径:C:\Windows\SysWOW64\FirewallAPI.dll

配置代码

以下是添加允许APP所有网络访问规则的示例代码。

using System;
using System.Collections.Generic;
using System.Text;
using NetFwTypeLib;
namespace FireWallTest
{
    public class FireWallHelp
    {
        public static void Main()
        {
            NetFwAllowAppsAll(App name, app absolute path);
        }
        
        public static void NetFwAllowAppsAll(string name, string executablePath)
        {
            INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID(HNetCfg.FWRule));
            firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
            firewallRule.Description = Allow all for   + name;
            firewallRule.ApplicationName = executablePath;
            firewallRule.Enabled = true;
            firewallRule.InterfaceTypes = All;
            firewallRule.Name = name;
            INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(
                Type.GetTypeFromProgID(HNetCfg.FwPolicy2));
            firewallPolicy.Rules.Add(firewallRule);
        }
    }
}

原文网址:https://www.cfnotes.com/archives/162 转载请注明出处

更新于:1个月前
赞一波!2

文章评论

全部评论