代码之家  ›  专栏  ›  技术社区  ›  Emir

如何使用C向windows firewall for sql server express添加异常#

  •  1
  • Emir  · 技术社区  · 14 年前

    我想使用C#向windows firewall for sql server express 2008 R2添加异常。

    我该怎么做?

    • 我有一个安装了Sql Server 2008 express R2数据库的应用程序,
    • 我想向防火墙添加例外,以便其他用户可以连接到数据库。(在sql express的配置文件中启用了TCP)

    4 回复  |  直到 14 年前
        1
  •  1
  •   Samuel Neff    14 年前
        2
  •  2
  •   kyndigs    14 年前

    Controlling Windows Firewall C#

    你也可以看看贴出的答案 here

        3
  •  1
  •   Matt    14 年前

    试试这个 link

    应该会成功的。

    编辑:

    Automating Windows Firewall Settings with C#

    你应该可以用这个打开你想要的端口

    1: INetFwOpenPorts ports; 
    2: INetFwOpenPort port; 
    3: port.Port = 1433; /* port no */
    4: port.Name = “Application1”; /*name of the application using the port */
    5: port.Enabled =  true; /* enable the port */
    6: /*other properties like Protocol, IP Version can also be set accordingly
    7: now add this to the GloballyOpenPorts collection */
    8: 
    9: Type NetFwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false); 
    10: INetFwMgr mgr = (INetFwMgr)Activator.CreateInstance(NetFwMgrType); 
    11: ports = (INetFwOpenPorts)mgr.LocalPolicy.CurrentProfile.GloballyOpenPorts; 
    12: 
    13: ports.Add(port);
    14: 
    

    注意在Visual Studio中,您需要添加 NetFwTypeLib COM using NetFwTypeLib; )

        4
  •  0
  •   Mahaveer Jangid    6 年前

    在这里,您可以通过C#为sql server 1433端口创建入站防火墙规则,该端口具有多配置文件域、公共和私有。

    首先,您必须从您的系统C:\ Windows\System32/FirewallAPI.dll导入一个dll。 将此DLL添加到项目引用中。

    添加dll之后,在代码中使用名称空间NetFwTypeLib,就像上面的程序一样。 使用NetFwTypeLib;

       using NetFwTypeLib;
       namespace ConsoleAppTestDemo
       {
        class Program
        {
         static void Main(string[] args)
         {
            Type tNetFwPolicy2 = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
            INetFwPolicy2 fwPolicy2 = (INetFwPolicy2)Activator.CreateInstance(tNetFwPolicy2);
    
            // Let's create a new rule
            INetFwRule2 inboundRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
            inboundRule.Enabled = true;
            //Allow through firewall
            inboundRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
    
            //For all profile
            inboundRule.Profiles = (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_ALL;
    
            //Using protocol TCP
            inboundRule.Protocol = 6; // TCP
            //Local Port 1433
            inboundRule.LocalPorts = "1433";
            //Name of rule
            inboundRule.Name = "SQLRule";
    
            // Now add the rule
            INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
            firewallPolicy.Rules.Add(inboundRule);
        }
    }
    

    之后,您可以检查防火墙入站规则。 enter image description here