设置 INetFwRule 的字符串成员时值超出范围异常

Value out of range exception when setting a string member of INetFwRule

我正在尝试为 TCP 端口 1433 添加防火墙规则,特定组使用 NetFwTypeLib 库。 但是将端口添加到 LocalPorts 变量中作为转换为字符串的整数或作为简单的“1433”字符串,returns 值超出范围异常。 删除端口并仅使用所有端口即可。

这是我使用的代码:

bool CreateRule(string sName, string sPort, NET_FW_IP_PROTOCOL_ ProtocolType, string sIpAdress, string sGroup = "")
{
    try
    {
        INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));

        firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
        firewallRule.Description = "Used to allow Server access.";
        firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
        firewallRule.Enabled = true;
        firewallRule.Name = sName;
        firewallRule.Grouping = sGroup;
        firewallRule.LocalPorts = sPort; // "1433" causes out of range exception
        firewallRule.RemoteAddresses = sIpAdress;
        firewallRule.Protocol = (int)ProtocolType;

        INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(
            Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
        firewallPolicy.Rules.Add(firewallRule);

        return true;
    }
    catch
    {
        return false;
    }
}

设置 firewallRule.LocalPorts 成员会导致异常。 有人知道出了什么问题吗?

您必须将协议类型放在端口之前,这样才有效。