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要有请求管理员权限。

C# .NET 操作Windows hosts的更多相关文章

  1. winreg操作windows注册表详解示例

    #coding:utf-8 #=====================================================================#=====本程序演示了WINR ...

  2. C语言操作WINDOWS系统存储区数字证书相关函数详解及实例

     C语言操作WINDOWS系统存储区数字证书相关函数详解及实例 以下代码使用C++实现遍历存储区证书及使用UI选择一个证书 --使用CertOpenSystemStore打开证书存储区. --在循环中 ...

  3. C# 操作windows服务[启动、停止、卸载、安装]

    主要宗旨:不已命令形式操作windows服务 static void Main(string[] args) { var path = @"E:\开发辅助项目\WCF\WCF.Test\WC ...

  4. 全键盘操作Windows

    计算机机用户在使用计算机的时候,是用键盘多一点?还是用鼠标多一点?如果是专业打字员,应该会说他使用键盘多一点,除此之外,多数人都会告诉你,他已经离不开鼠标了,没有鼠标,就不会操作电脑.   如果某一天 ...

  5. C#通过SC命令和静态公共类来操作Windows服务

    调用的Windows服务应用程序网址:http://www.cnblogs.com/pingming/p/5115304.html 一.引用 二.公共静态类:可以单独放到类库里 using Syste ...

  6. cmd命令行和bat批处理操作windows服务(转载)

    一.cmd命令行---进行Windows服务操作 1.安装服务 sc create 服务名 binPath= "C:\Users\Administrator\Desktop\win32srv ...

  7. (转)Python 操作 Windows 粘贴板

    转自: http://outofmemory.cn/code-snippet/3939/Python-operation-Windows-niantie-board Python 操作 Windows ...

  8. C#使用DirectoryEntry类操作Windows帐户

    1.创建windows帐户 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 /// <summary> /// 创建Windows帐户 /// </summa ...

  9. [经验分享]C# 操作Windows系统计划任务

    背景:我做了一个事情是要自己提前创建好很多要定时执行的任务,在我不在的时候自动执行这些程序,以保证我的工作能无人值守,那么我就需要建立系统计划任务来帮我完成这件事情,当然用脑子想想如何实现,很简单,每 ...

  10. C#.NET 操作Windows服务承载WCF

    Windows服务的制作.安装可以参考这篇: C#.NET 操作Windows服务(安装.卸载) - runliuv - 博客园 (cnblogs.com) 本篇会在这个解决方案基础上,继续修改. 一 ...

随机推荐

  1. 阿里云 EMAS Serverless 重磅发布

    简介: EMAS Serverless 是阿里云提供的基于Serverless技术的一站式后端开发平台,为开发者提供高可用.弹性伸缩的云开发服务,包含云函数.云数据库.云存储.静态网站托管等功能,可用 ...

  2. MySQL 深潜 - MDL 锁的实现与获取机制

    简介:本文将介绍在 MDL 系统中常用的数据结构及含义,然后从实现角度讨论 MDL 的获取机制与死锁检测,最后分享在实践中如何监控 MDL 状态. ​ 作者 | 泊歌 来源 | 阿里技术公众号 一 背 ...

  3. 殷浩详解DDD:领域层设计规范

    简介: 在一个DDD架构设计中,领域层的设计合理性会直接影响整个架构的代码结构以及应用层.基础设施层的设计.但是领域层设计又是有挑战的任务,特别是在一个业务逻辑相对复杂应用中,每一个业务规则是应该放在 ...

  4. 延迟绑定与retdlresolve

    延迟绑定与retdlresolve 我们以前在ret2libc的时候,我们泄露的libc地址是通过延迟绑定实现的,我们知道,在调用libc里面的函数时候,它会先通过plt表和gor表绑定到,函数真实地 ...

  5. [MySQL] 原生全文检索 fulltext 的简单应用

    在目标字段上添加全文检索:alter table 表名 add fulltext(字段) with parser ngram 查询语句:select * from xxx where match(字段 ...

  6. WPF 已知问题 RadioButton 指定 GroupName 后关闭窗口可能导致无法选中

    本文记录一个 WPF 已知问题,当 WPF 的 RadioButton 指定 GroupName 且将 IsChecked 状态绑定到 ViewModel 上,将包含以上控件的代码的窗口显示两个,接着 ...

  7. 2019-11-29-C#-如何写-DEBUG-输出

    title author date CreateTime categories C# 如何写 DEBUG 输出 lindexi 2019-11-29 08:28:35 +0800 2018-2-13 ...

  8. 2018-2-13-win10-uwp-右击选择-GridViewItem-

    title author date CreateTime categories win10 uwp 右击选择 GridViewItem lindexi 2018-2-13 17:23:3 +0800 ...

  9. rails 写入日志函数

    json_object={ "ip"=> "127.0.0.1", "ports"=> '80,135', "data ...

  10. Linux中文件的隐藏属性

    在Linux系统中,可以使用chattr与lsattr来操作文件的隐藏属性.