找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 135|回复: 0

[工具类] C# 操作Hosts 新增修改删除

[复制链接] IP属地:广东省广州市荔湾区
发表于 2024-6-12 12:34:20 | 显示全部楼层 |阅读模式
  1. class ModifyHosts
  2. {
  3.     /// <summary>
  4.     /// 新增hosts记录
  5.     /// </summary>
  6.     /// <param name="ip"></param>
  7.     /// <param name="domain"></param>
  8.     public static void Add_Hosts(string domain, string ip)
  9.     {
  10.         string path = Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\drivers\\etc\\hosts";
  11.         string[] hosts = File.ReadAllLines(path);
  12.         List<string> list = hosts.ToList();
  13.         string temp = hosts.ToList().FirstOrDefault(x => x.Contains(domain));
  14.         if (string.IsNullOrEmpty(temp))
  15.         {
  16.             list.Add($"{ip} {domain}");
  17.         }
  18.         File.WriteAllLines(path, list.ToArray());
  19.     }
  20.     /// <summary>
  21.     /// 更新Hosts记录
  22.     /// </summary>
  23.     /// <param name="ip"></param>
  24.     /// <param name="domain"></param>
  25.     public static void Update_Hosts(string domain, string ip)
  26.     {
  27.         string path = Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\drivers\\etc\\hosts";
  28.         string[] hosts = File.ReadAllLines(path);
  29.         List<string> list = hosts.ToList();
  30.         list.RemoveAll(x => x.Contains(domain));
  31.         list.Add($"{ip} {domain}");
  32.         File.WriteAllLines(path, list.ToArray());
  33.     }

  34.     /// <summary>
  35.     /// 删除Hosts记录
  36.     /// </summary>
  37.     /// <param name="hosts_str"></param>
  38.     public static void Remove_Hosts(string hosts_str)
  39.     {
  40.         string path = Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\drivers\\etc\\hosts";
  41.         string[] hosts = File.ReadAllLines(path);
  42.         List<string> list = hosts.ToList();
  43.         list.RemoveAll(x => x.Contains(hosts_str));
  44.         File.WriteAllLines(path, list.ToArray());
  45.     }
  46. }
复制代码


您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|西兴社区 ( 蜀ICP备2022005627号 )|网站地图

GMT+8, 2024-12-27 09:28 , Processed in 0.631264 second(s), 21 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表