我们有一个应用程序可以为防火墙添加一些规则。我们需要检索防火墙规则,以便我们检查防火墙中是否存在该规则。 我正在使用C#。
答案 0 :(得分:0)
您可以从此代码中获得一个想法。
INetFwPolicy2 fwPolicy2 = (INetFwPolicy2)Activator.CreateInstance(typeFWPolicy2);
List<INetFwRule> RuleList = new List<INetFwRule>();
foreach (INetFwRule rule in fwPolicy2.Rules)
{
RuleList.Add(rule);
}
答案 1 :(得分:0)
EDITED: INetFwPolicy2是一个用于管理防火墙规则的.Net界面msdn INetFwPolicy2有一个规则集合,包含此策略的所有规则。 您可以使用Lambda查询Rules集合,如下所示:
INetFwPolicy2 fwPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
fwPolicy2.Rules.OfType<INetFwRule>.Select....
以及所有其他Lambda扩展。
答案 2 :(得分:0)
使用规则名称搜索防火墙规则并将其删除:
public static void RemoveFirewallRules(string RuleName)
{
try
{
Type tNetFwPolicy2 = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
INetFwPolicy2 fwPolicy2 = (INetFwPolicy2)Activator.CreateInstance(tNetFwPolicy2);
var currentProfiles = fwPolicy2.CurrentProfileTypes;
// List of rules
// List<INetFwRule> RuleList = new List<INetFwRule>();
foreach (INetFwRule rule in fwPolicy2.Rules)
{
// Add a rule to list
// RuleList.Add(rule);
// Console.WriteLine(rule.Name);
if (rule.Name.IndexOf(RuleName) != -1)
{
// Remove a rule
INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
firewallPolicy.Rules.Remove(rule.Name);
Console.WriteLine(rule.Name + " has been deleted from the Firewall Policy");
}
}
}
catch (Exception r)
{
Console.WriteLine("Error deleting a Firewall rule");
}
}
答案 3 :(得分:0)
如果您不想添加对提供INetFwPolicy2接口的程序集的引用,则可以在C#中使用the dynamic class来反映“ HNetCfg.FwPolicy2”类型。参见以下工作代码:
Type tNetFwPolicy2 = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
dynamic fwPolicy2 = Activator.CreateInstance(tNetFwPolicy2) as dynamic;
IEnumerable Rules = fwPolicy2.Rules as IEnumerable;
foreach (dynamic rule in Rules)
{
if (rule.Name=="My firewall rule")
{
}
}
请注意,以这种方式使用动态对象需要引用Microsoft.CSharp程序集。