注意程序需要管理员权限
using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Text;using System.Threading.Tasks;namespace SetHosts{ internal class Program { static void Main(string[] args) { Hosts_UP.Set_Hosts("microsoft.gointeract.io", "23.101.130.247"); Hosts_UP.Remove_Hosts("microsoft.gointeract.io"); } public class Hosts_UP { public static void Set_Hosts(string domain, string ip) { string path = System.Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\drivers\\etc\\hosts"; string[] hosts = File.ReadAllLines(path); List<string> list = hosts.ToList(); string temp = hosts.ToList().FirstOrDefault(x => x.Contains(domain)); if (string.IsNullOrEmpty(temp)) { list.Add($"{ip} {domain}"); } File.WriteAllLines(path, list.ToArray()); } public static void Remove_Hosts(string hosts_str) { string path = System.Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\drivers\\etc\\hosts"; string[] hosts = File.ReadAllLines(path); List<string> list = hosts.ToList(); //int index = list.FindIndex(x => x.Contains(hosts_str)); //list.RemoveAt(index); list.RemoveAll(x => x.Contains(hosts_str)); //foreach (string item in list.ToArray()) //{ // if (item.Contains(hosts_str)) // { // list.Remove(item); // } //} File.WriteAllLines(path, list.ToArray()); } } }}
推荐本站淘宝优惠价购买喜欢的宝贝:
本文链接:https://hqyman.cn/post/3066.html 非本站原创文章欢迎转载,原创文章需保留本站地址!
休息一下~~