使用C#操作Windows防火墙

作者:cnchanghai , 分类:编程学习 , 浏览:540 , 评论:

在公司内部网络内,计算机的系统防火墙会给管理员造成管理上的不便。所以在很多情况下,我们都是将系统防火墙给关闭掉。使用C#操作防火墙的代码如下:

首先是获取防火墙状态

private void get_fw()
        {
            RegistryKey sdfw = Registry.LocalMachine.OpenSubKey(@"SYSTEM\\CurrentControlSet\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\StandardProfile", true);
            RegistryKey dmfw = Registry.LocalMachine.OpenSubKey(@"SYSTEM\\CurrentControlSet\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\DomainProfile", true);
            RegistryKey pubfw = Registry.LocalMachine.OpenSubKey(@"SYSTEM\\CurrentControlSet\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\PublicProfile", true);
            var sdfwpf = sdfw.GetValue("EnableFirewall").ToString();//专用网络防火墙
            var dmfwpf = dmfw.GetValue("EnableFirewall").ToString();//网域网络防火墙
            var pubfwpf = pubfw.GetValue("EnableFirewall").ToString();//公用网络防火墙
            if(sdfwpf =="0" && dmfwpf =="0" && pubfwpf == "0")
            {
                this.fw_txt.Text = "防火墙已关闭";
            }
            else
            {
                this.fw_txt.Text = "防火墙已开启";
                this.fw_btn.Show();//显示关闭防火墙按钮
            }         
        }

 

关闭防火墙

private void fw_btn_Click(object sender, EventArgs e)
        {
            RegistryKey sdfw = Registry.LocalMachine.OpenSubKey(@"SYSTEM\\CurrentControlSet\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\StandardProfile", true);
            RegistryKey dmfw = Registry.LocalMachine.OpenSubKey(@"SYSTEM\\CurrentControlSet\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\DomainProfile", true);
            RegistryKey pubfw = Registry.LocalMachine.OpenSubKey(@"SYSTEM\\CurrentControlSet\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\PublicProfile", true);
            sdfw.SetValue("EnableFirewall", 0); //专用网络防火墙
            dmfw.SetValue("EnableFirewall", 0); //网域网络防火墙
            pubfw.SetValue("EnableFirewall", 0);//公用网络防火墙
            ServiceController fwsrv = new ServiceController("MpsSvc");
            fwsrv.Stop();
            fwsrv.WaitForStatus(ServiceControllerStatus.Stopped);
            fwsrv.Start();
            fwsrv.WaitForStatus(ServiceControllerStatus.Running);
            fwsrv.Close();
            get_fw();//重新刷新防火墙状态
        }

李长海的博客