Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 设置INetFwRule的字符串成员时出现值超出范围异常_C#_Exception_Firewall - Fatal编程技术网

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

C# 设置INetFwRule的字符串成员时出现值超出范围异常,c#,exception,firewall,C#,Exception,Firewall,我正在尝试为TCP端口1433添加一个防火墙规则,其中一个特定组使用NetFwTypeLib库。 但将端口作为转换为字符串的整数或简单的“1433”字符串添加到LocalPorts变量中,会返回一个超出范围的值异常。 移除端口并仅使用所有端口都可以正常工作 以下是我使用的代码: bool CreateRule(string sName, string sPort, NET_FW_IP_PROTOCOL_ ProtocolType, string sIpAdress, string sGroup

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

以下是我使用的代码:

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
成员会导致异常。
有人知道出了什么问题吗?

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

可以确认。在PoSH中,如果您在分配
$rule.Protocol
之前尝试分配
$rule.localport
,您将得到一个异常。此外,如果协议设置为“any”端口,则将不允许。