C# .NET 操作Windows hosts
工具类HostsUtil:
using System; using System.IO; using System.Text; namespace CommonUtils { public static class HostsUtil { public static string GetHostFileFullName() { string abc = Environment.GetEnvironmentVariable("systemroot"); string fileName = Path.Combine(abc, @"System32\drivers\etc\hosts"); return fileName; } /// <summary> /// 域名是否存在 /// </summary> /// <param name="hostsLineValue">格式:api.yun.comn</param> /// <returns></returns> public static bool IsDomainEx(string inputValue) { string fileName = GetHostFileFullName(); //兼容 IP+空格+域名 string domain = inputValue; if (!string.IsNullOrEmpty(inputValue) && inputValue.Trim().Contains(" ")) { var hostLineArray = inputValue.Trim().Split(' '); if (hostLineArray.Length > 1) { domain = hostLineArray[1]; } } using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { using (StreamReader sr = new StreamReader(fs, Encoding.UTF8)) { while (sr.Peek() >= 0) { string curLine = sr.ReadLine(); if (!string.IsNullOrEmpty(curLine) && !curLine.Trim().StartsWith("#")) { var hostLineArray = curLine.Trim().Split(' '); if (hostLineArray.Length > 1) { string lineDomain = hostLineArray[1]; if (!string.IsNullOrEmpty(lineDomain) && lineDomain.Trim() == domain) { return true; } } } } } } return false; } /// <summary> /// 删除域名绑定 /// </summary> /// <param name="hostsLineValue">格式:api.yun.comn</param> /// <returns></returns> public static bool Del(string inputValue) { string fileName = GetHostFileFullName(); if (!IsDomainEx(inputValue)) { //不存在返回,视为成功。 return true; } //兼容 IP+空格+域名 string domain = inputValue; if (!string.IsNullOrEmpty(inputValue) && inputValue.Trim().Contains(" ")) { var hostLineArray = inputValue.Trim().Split(' '); if (hostLineArray.Length > 1) { domain = hostLineArray[1]; } } StringBuilder scHosts = new StringBuilder(); //修改 using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { using (StreamReader sr = new StreamReader(fs, Encoding.UTF8)) { while (sr.Peek() >= 0) { string curLine = sr.ReadLine(); //只处理非#号开头的,微软的原注释保留 if (!string.IsNullOrEmpty(curLine) && !curLine.Trim().StartsWith("#")) { var hostLineArray = curLine.Trim().Split(' '); if (hostLineArray.Length > 1) { string lineDomain = hostLineArray[1]; if (!string.IsNullOrEmpty(lineDomain) && lineDomain.Trim() == domain) { //如果是要删除的那行,直接跳过 continue; } } } scHosts.AppendLine(curLine); } } } //使hosts文件可写 FileInfo ff = new FileInfo(fileName); if (ff.Attributes != FileAttributes.Normal) { File.SetAttributes(fileName, FileAttributes.Normal); } string hostsContent = scHosts.ToString(); //写 using (FileStream fs = new FileStream(fileName, FileMode.Truncate, FileAccess.Write)) { using (StreamWriter sr = new StreamWriter(fs, Encoding.UTF8)) { sr.Write(hostsContent); } } return true; } /// <summary> /// 添加或修改域名绑定 /// </summary> /// <param name="hostsLineValue">格式:192.168.0.33 api.yun.comn</param> /// <returns></returns> public static bool AddOrEdit(string inputValue) { inputValue = inputValue.Trim();//去除前后空格 if (!inputValue.Trim().Contains(" ")) { throw new Exception("非法域名绑定!"); } string fileName = GetHostFileFullName(); if (IsDomainEx(inputValue)) { //存在则先删除旧的。新旧要绑定的IP可能会不一样。 Del(inputValue); } //使hosts文件可写 FileInfo ff = new FileInfo(fileName); if (ff.Attributes != FileAttributes.Normal) { File.SetAttributes(fileName, FileAttributes.Normal); } bool writeEmptyLine = false; string orgCon = GetHostsContent(); if (!orgCon.EndsWith("\r\n")) { writeEmptyLine = true; } //修改 using (FileStream fs = new FileStream(fileName, FileMode.Append, FileAccess.Write)) { using (StreamWriter sr = new StreamWriter(fs, Encoding.UTF8)) { if (writeEmptyLine) { //非换行结尾的,添加上换行。 //避免出现 “192.168.0.7 cn.bing.co5192.168.0.8 cn.bing.co6” sr.Write("\r\n"); } sr.WriteLine(inputValue); } } return true; } public static string GetHostsContent() { string con = string.Empty; string fileName = GetHostFileFullName(); if (!File.Exists(fileName)) { return con; } using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { using (StreamReader sr = new StreamReader(fs, Encoding.UTF8)) { con = sr.ReadToEnd(); } } return con; } } }
使用:
添加或编辑:
HostsUtil.AddOrEdit("192.168.3.33 www.api.com");
删除:
HostsUtil.Del("www.api.com");
注意:WINFORM要有请求管理员权限。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
2019-11-22 C#.NET LoadXml 时 “根级别上的数据无效。 行 1,位置 1”
2019-11-22 C#.NET 合并图片
2018-11-22 获取本目录及子目录下所有文件
2013-11-22 深圳市罗湖区深南东路2097号 深圳远东妇儿医院