C# 控制台应用windows修改host文件

发布时间 2023-04-11 16:42:14作者: 阿飞飞阿飞

配置文件修改

App.config部分主要是IP与地址

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
    </startup>
  <appSettings>    
    <add key="IP" value="192.168.16.105"/>
    <add key="Address" value="www.jymfxy2.vip"/>
  </appSettings>
</configuration>

代码部分

Program

 // IP
            string IP = ConfigurationSettings.AppSettings["IP"];
            // 地址
            string Address = ConfigurationSettings.AppSettings["Address"];

            // 获取hosts文件路径
            string hostsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), @"drivers\etc\hosts");

            //删除掉之前的
            string filePath = hostsPath;
            string[] lines = File.ReadAllLines(filePath);
            string[] filteredLines = lines.Where(line => !line.Contains(Address)).ToArray();
            File.WriteAllLines(filePath, filteredLines);

            // 打开文件并写入新的地址信息
            using (StreamWriter writer = new StreamWriter(hostsPath, true))
            {
                writer.WriteLine($"{IP} {Address}"); // 添加新的地址信息
            }

            // 读取文件并显示内容
            using (StreamReader reader = new StreamReader(hostsPath))
            {
                string content = reader.ReadToEnd();
                Console.WriteLine(content);
            }

            Console.WriteLine("注入修改完成!");
            // 等待消息
            Console.ReadLine();

调试运行会提示权限,写好后直接生成,然后去debug里面寻找应用----右键-管理员的权限打开即可