24
2022
11
09:25:56

C#操作修改hosts



推荐点击下面图片,通过本站淘宝优惠价购买:

image.png

注意程序需要管理员权限

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 非本站原创文章欢迎转载,原创文章需保留本站地址!

分享到:





休息一下,本站随机推荐观看栏目:


« 上一篇 下一篇 »

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

您的IP地址是: