通过代码操作防火墙的方式有两种:一是代码操作修改注册表启用或关闭防火墙;二是直接操作防火墙对象来启用或关闭防火墙。不论哪一种方式,都需要使用管理员权限,所以操作前需要判断程序是否具有管理员权限。

  1、判断程序是否拥有管理员权限

  需要引用命名空间:system.security.principal

/// <summary>
/// 判断程序是否拥有管理员权限
/// </summary>
/// <returns>true:是管理员;false:不是管理员</returns>
public static bool isadministrator()
{
  windowsidentity current = windowsidentity.getcurrent();
  windowsprincipal windowsprincipal = new windowsprincipal(current);
  return windowsprincipal.isinrole(windowsbuiltinrole.administrator);
}

  2、注册表修改防火墙

  需要引用命名空间:microsoft.win32

/// <summary>
/// 通过注册表操作防火墙
/// </summary>
/// <param name="domainstate">域网络防火墙(禁用:0;启用(默认):1)</param>
/// <param name="publicstate">公共网络防火墙(禁用:0;启用(默认):1)</param>
/// <param name="standardstate">专用网络防火墙(禁用:0;启用(默认):1)</param>
/// <returns></returns>
public static bool firewalloperatebyregistrykey(int domainstate=1, int publicstate = 1, int standardstate = 1)
{
  registrykey key = registry.localmachine;
  try
  {
    string path = "hkey_local_machine\\system\\controlset001\\services\\sharedaccess\\defaults\\firewallpolicy";
    registrykey firewall = key.opensubkey(path, true);
    registrykey domainprofile = firewall.opensubkey("domainprofile", true);
    registrykey publicprofile = firewall.opensubkey("publicprofile", true);
    registrykey standardprofile = firewall.opensubkey("standardprofile", true);
    domainprofile.setvalue("enablefirewall", domainstate, registryvaluekind.dword);
    publicprofile.setvalue("enablefirewall", publicstate, registryvaluekind.dword);
    standardprofile.setvalue("enablefirewall", standardstate, registryvaluekind.dword);
  }
  catch (exception e)
  {
    string error = $"注册表修改出错:{e.message}";
    throw new exception(error);
  }
  return true;
}

   3、直接操作防火墙对象

  需要在项目引用中添加对netfwtypelib的引用,并引用命名空间netfwtypelib

/// <summary>
/// 通过对象防火墙操作
/// </summary>
/// <param name="isopendomain">域网络防火墙(禁用:false;启用(默认):true)</param>
/// <param name="isopenpublicstate">公共网络防火墙(禁用:false;启用(默认):true)</param>
/// <param name="isopenstandard">专用网络防火墙(禁用: false;启用(默认):true)</param>
/// <returns></returns>
public static bool firewalloperatebyobject(bool isopendomain = true, bool isopenpublicstate = true, bool isopenstandard = true)
{
  try
  {
    inetfwpolicy2 firewallpolicy = (inetfwpolicy2)activator.createinstance(type.gettypefromprogid("hnetcfg.fwpolicy2"));
    // 启用<高级安全windows防火墙> - 专有配置文件的防火墙
    firewallpolicy.set_firewallenabled(net_fw_profile_type2_.net_fw_profile2_private, isopenstandard);
    // 启用<高级安全windows防火墙> - 公用配置文件的防火墙
    firewallpolicy.set_firewallenabled(net_fw_profile_type2_.net_fw_profile2_public, isopenpublicstate);
    // 启用<高级安全windows防火墙> - 域配置文件的防火墙
    firewallpolicy.set_firewallenabled(net_fw_profile_type2_.net_fw_profile2_domain, isopendomain);
  }
  catch (exception e)
  {
    string error = $"防火墙修改出错:{e.message}";
    throw new exception(error);
  }
  return true;
}

以上就是c# 通过代码开启或关闭防火墙的详细内容,更多关于c# 防火墙的资料请关注www.887551.com其它相关文章!