【转载】【有效】.NET Framework 4.0 添加 Windows 应用程序到系统防火墙

文章介绍了如何在.NETCore应用程序中使用WindowsIdentity和WindowsFirewallAPI,实现在启动时自动将应用添加到Windows防火墙的白名单,包括公共、专用和域等不同网络类型。作者还提供了源代码示例和版权信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    using System;
    using System.IO;
#if NETCOREAPP
    using System.Runtime.CompilerServices;
#endif
    using System.Runtime.InteropServices;
    using System.Security.Principal;
 
    public static class Fw
    {
#if NETCOREAPP
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
        public static bool IsAdministrator()
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);
            return principal.IsInRole(WindowsBuiltInRole.Administrator);
        }
 
#if NETCOREAPP
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
        public static void NetFirewallAddAllApplication(string name, string executablePath)
        {
            if (!Fw.NetFirewallAddApplication(name, executablePath))
            {
                for (int c = 0; c < 3; c++)
                {
                    bool ok = Fw.NetFirewallAddApplication(name, executablePath, 1)
                        & Fw.NetFirewallAddApplication(name, executablePath, 2);
                    if (ok)
                    {
                        break;
                    }
                }
            }
        }
 
#if NETCOREAPP
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
        public static bool NetFirewallAddApplication(string name, string executablePath, int netFwType)
        {
            if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(executablePath))
            {
                return false;
            }
            if (!File.Exists(executablePath))
            {
                return false;
            }
            dynamic netFwMgr = null;
            dynamic netFwProfile = null;
            dynamic netFwApp = null;
            try
            {
                netFwMgr = Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwMgr"));
                netFwProfile = netFwMgr.LocalPolicy.GetProfileByType(netFwType);
                netFwApp = Activator.
                    CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwAuthorizedApplication"));
 
                // 在例外列表里,程序显示的名称
                netFwApp.Name = name;
 
                // 程序的路径及文件名
                netFwApp.ProcessImageFileName = executablePath;
 
                // 是否启用该规则
                netFwApp.Enabled = true;
 
                // 加入到防火墙的管理策略
                netFwProfile.AuthorizedApplications.Add(netFwApp);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
            finally
            {
                object[] comObjects = { netFwMgr, netFwProfile, netFwApp };
                foreach (object comObject in comObjects)
                {
                    if (comObject == null)
                    {
                        continue;
                    }
                    IDisposable disposable = comObject as IDisposable;
                    if (disposable != null)
                    {
                        disposable.Dispose();
                    }
                    Marshal.ReleaseComObject(comObject);
                    Marshal.FinalReleaseComObject(comObject);
                }
            }
        }
 
#if NETCOREAPP
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
        public static bool NetFirewallAddApplication(string name, string executablePath)
        {
            dynamic rule = null;
            dynamic policy = null;
            dynamic rules = null;
            try
            {
                policy = Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
                rules = policy.Rules;
                foreach (dynamic i in rules)
                {
                    if (i.Name == name)
                    {
                        if (i.ApplicationName == executablePath)
                        {
                            rules.Remove(name);
                        }
                    }
                }
                rule = Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
                rule.Name = name;
                rule.Description = name;
                rule.ApplicationName = executablePath;
                rule.Direction = 1;
                rule.Action = 1;
                rule.Enabled = true;
                rules.Add(rule);
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                object[] comObjects = { rule, rules, policy };
                foreach (object comObject in comObjects)
                {
                    if (comObject == null)
                    {
                        continue;
                    }
                    IDisposable disposable = comObject as IDisposable;
                    if (disposable != null)
                    {
                        disposable.Dispose();
                    }
                    Marshal.ReleaseComObject(comObject);
                    Marshal.FinalReleaseComObject(comObject);
                }
            }
        }
    }

假设我们希望应用程序在启动时则自动配置系统防火墙该怎么实现呢?

添加本程序到 Windows 系统防火墙:(打开,公共、专用、域白名单)

Fw.NetFirewallAddAllApplication(MyApplication.ApplicationName, Process.GetCurrentProcess().MainModule.FileName);

注意:netFwType 类型范围为:0~3,分别对应:公共、专用、域等,具体效果可自行带代码调试查看。

操作 Windows 系统防火墙的源实现:
————————————————
版权声明:本文为CSDN博主「liulilittle」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/liulilittle/article/details/122605775

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值