C# .NET 操作Windows hosts
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的更多相关文章
- winreg操作windows注册表详解示例
#coding:utf-8 #=====================================================================#=====本程序演示了WINR ...
- C语言操作WINDOWS系统存储区数字证书相关函数详解及实例
C语言操作WINDOWS系统存储区数字证书相关函数详解及实例 以下代码使用C++实现遍历存储区证书及使用UI选择一个证书 --使用CertOpenSystemStore打开证书存储区. --在循环中 ...
- C# 操作windows服务[启动、停止、卸载、安装]
主要宗旨:不已命令形式操作windows服务 static void Main(string[] args) { var path = @"E:\开发辅助项目\WCF\WCF.Test\WC ...
- 全键盘操作Windows
计算机机用户在使用计算机的时候,是用键盘多一点?还是用鼠标多一点?如果是专业打字员,应该会说他使用键盘多一点,除此之外,多数人都会告诉你,他已经离不开鼠标了,没有鼠标,就不会操作电脑. 如果某一天 ...
- C#通过SC命令和静态公共类来操作Windows服务
调用的Windows服务应用程序网址:http://www.cnblogs.com/pingming/p/5115304.html 一.引用 二.公共静态类:可以单独放到类库里 using Syste ...
- cmd命令行和bat批处理操作windows服务(转载)
一.cmd命令行---进行Windows服务操作 1.安装服务 sc create 服务名 binPath= "C:\Users\Administrator\Desktop\win32srv ...
- (转)Python 操作 Windows 粘贴板
转自: http://outofmemory.cn/code-snippet/3939/Python-operation-Windows-niantie-board Python 操作 Windows ...
- C#使用DirectoryEntry类操作Windows帐户
1.创建windows帐户 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 /// <summary> /// 创建Windows帐户 /// </summa ...
- [经验分享]C# 操作Windows系统计划任务
背景:我做了一个事情是要自己提前创建好很多要定时执行的任务,在我不在的时候自动执行这些程序,以保证我的工作能无人值守,那么我就需要建立系统计划任务来帮我完成这件事情,当然用脑子想想如何实现,很简单,每 ...
- C#.NET 操作Windows服务承载WCF
Windows服务的制作.安装可以参考这篇: C#.NET 操作Windows服务(安装.卸载) - runliuv - 博客园 (cnblogs.com) 本篇会在这个解决方案基础上,继续修改. 一 ...
随机推荐
- 力扣119(java)-杨辉三角Ⅱ(简单)
题目: 给定一个非负索引 rowIndex,返回「杨辉三角」的第 rowIndex 行. 在「杨辉三角」中,每个数是它左上方和右上方的数的和. 示例 1: 输入: rowIndex = 3输出: [1 ...
- Dapr 在阿里云原生的实践
简介: Faas 场景下,比较吸引用户的是成本和研发效率,成本主要通过按需分配和极致的弹性效率来达成.而应用开发者期望通过 FaaS 提供多语言的编程环境,提升研发效率,包括启动时间.发布时间.开发的 ...
- [Contract] Truffle 使用流程
Installation $ npm install -g truffle Choose ethereum client (Ganache OR truffle build in `truffle d ...
- dotnet 使用 windbg 运行脚本方式自动批量调试处理 dump 文件
本文将和大家介绍一个简单且实际用途不大的使用 windbg 配合脚本的方式,进行自动化的大批量对 dotnet 系应用的 dump 进行自动化分析调试处理,可以自动根据调试需求输出 dump 文件的一 ...
- 5.prometheus监控--监控nginx
1.监控程序环境准备 mkdir /data/docker-compose -p cd /data/docker-compose cat > docker-compose.yaml <&l ...
- Oracle和达梦:查询系统表、系统表字段
1.查询系统表 当前模式下所有的表 可以查询到:表名.表注释 select * from user_tab_comments where TABLE_TYPE = 'TABLE' 2.查询系统表字段 ...
- 6、Samba 文件共享服务
1.Samba 服务基础 SMB(Server Message Block),服务消息块 CIFS(Common Internet File System),通用互联网文件系统 Samba 项目:ht ...
- Python基础知识——缩进、标识符、保留字
标识符 标识符就是程序中,使用的各种名称,例如:变量名.常量名.类名等等. 在 Python 中,对标识符格式的要求与 C/C++.Java 等差不多: 第一个字符必须是字母表中的字母或下划线 _ ; ...
- IDEA的Ctrl+Enter补全代码失效
前景提示 IDEA有个ctrl+enter可以补全代码的功能,但是,今天突然失效了,原来是这个问题. 修改配置 进入setting修改 进入Edit-->找到Intertions,搜素Intro ...
- AIRIOT赋能水务行业深度转型,打造智慧水务“四化建设”
水利水务与民生息息相关,随着我国智慧城市建设的推进及科学技术的不断发展,对城市供水管理产生了尤为重要的影响.面对水务行业信息化建设周期长,无统一的技术标准和数据标准,信息孤岛严重,协同工作能力受制 ...