vs2010 c# 管理win7防火墙

1. 概述

在Win7中运行的网络应用程序需要防火墙中增加许可规则。利用C#实现在防火墙自动添加入站端口许可规则。程序开发环境为vs2010旗舰版。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.Common;

namespace FirewallAutomation
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建防火墙管理器实例。这里用到了COM
            Type netfwType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false);
            INetFwMgr mgr = (INetFwMgr)Activator.CreateInstance(netfwType);
            
            //获取端口列表
            INetFwOpenPorts ports = (INetFwOpenPorts)mgr.LocalPolicy.CurrentProfile.GloballyOpenPorts;
            System.Collections.IEnumerator enumerate = ports.GetEnumerator();
            while (enumerate.MoveNext())
            {
                INetFwOpenPort port = (INetFwOpenPort)enumerate.Current;
                Console.WriteLine("Name:{0}  Protocol:{1}, Port:{2}", port.Name, port.Protocol.ToString(),port.Port);
            }

            //在入站规则中添加新的端口许可:TCP协议、8003端口
            INetFwOpenPort newPort = (INetFwOpenPort)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwOpenPort"));
            newPort.Port = 8003;
            newPort.Name = "放行8003";
            newPort.Protocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
            newPort.Enabled = true;
            ports.Add(newPort);

        }
    }
}

2. 运行结果

3. 注意点

 程序必须获取UAC!

转载于:https://www.cnblogs.com/protorock/archive/2013/01/29/2881406.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值