添加防火墙规则不添加域网络

时间:2013-12-26 10:28:28

标签: c# firewall windows-firewall windows-firewall-api

我正在尝试在防火墙中添加应用程序。它工作正常,但它只检查“公共”选项。我想为“域”添加防火墙规则。

这是我的代码。

private const string ClsidFirewallManager = "{304CE942-6E39-40D8-943A-B913C40C9CD4}";

private INetFwMgr _firewallManager;
private INetFwMgr FirewallMgr
{
    get { return _firewallManager ?? (_firewallManager = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(ClsidFirewallManager)))); }
}

private INetFwPolicy FirewallPolicy
{
    get { return FirewallMgr.LocalPolicy; }
}

private INetFwProfile _firewallProfile;
private INetFwProfile FirewallProfile
{
    get { return _firewallProfile ?? (_firewallProfile = FirewallPolicy.CurrentProfile); }
}


public void AddApplication(string imageFileName, string registerName)
{
    if (!IsAppEnabled(imageFileName))
    {
        var firewallApplicatoins = FirewallProfile.AuthorizedApplications;
        var type = Type.GetTypeFromProgID("HNetCfg.FwAuthorizedApplication");
        var firewallApplication = Activator.CreateInstance(type) as INetFwAuthorizedApplication;

            firewallApplication.ProcessImageFileName = imageFileName;
            firewallApplication.Name = registerName;
            firewallApplication.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_LOCAL_SUBNET; ---> Here it adds to public, whatever the value for enum is.
            firewallApplication.Enabled = true;

            firewallApplicatoins.Add(firewallApplication);
    }
}

我已关注此链接。

http://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/10c6ff4b-701b-4351-a3d8-a716d8831a66/add-c-application-to-firewall-exception-list-of-windows-7?forum=windowssecurity&prof=required

现在,无论我为Scope分配什么值,都只为公共网络添加防火墙规则。我想将其添加到域网络中。

firewallApplication.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_LOCAL_SUBNET;

我在这里做错了什么。我使用的是Windows 8。

1 个答案:

答案 0 :(得分:0)

我遇到了问题。我现有的代码仅适用于Windows XP。对于Vista或更高版本,它无法正常工作。对于Vista,我需要使用下一版本的防火墙。

这是代码。

var firewallRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));

firewallRule.Name = registerName;
firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
firewallRule.Enabled = true;
firewallRule.InterfaceTypes = "All";

var rules = VistaFirewallPolicy.Rules;
rules.Add(firewallRule);

此代码会将防火墙规则添加到域,私人和公共。