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) 本篇会在这个解决方案基础上,继续修改. 一 ...
随机推荐
- 剑指offer05(Java)-替换空格(简单)
题目: 请实现一个函数,把字符串 s 中的每个空格替换成"%20". 示例 1: 输入:s = "We are happy."输出:"We%20are ...
- [FAQ] 对于 Puppeteer 和 Chromium 在 Linux 上的安装,需要安装哪些依赖库
比如 puppeteer/chrome/linux-114.0.5735.133/chrome-linux64/chrome 到底要装哪些依赖. 一般根据报错提示,安装缺少的即可,以下是一般需要的 ...
- [Contract] Solidity 合约使用 truffle 部署到测试网和主网
使用 truffle 发布到非本地的以太坊主网或者测试网时,需要提供钱包的助记词或私钥. 首先安装 truffle 组件:npm install @truffle/hdwallet-provider ...
- WPF 实现自定义的笔迹橡皮擦
本文来告诉大家使用比较底层的方法来实现 WPF 的笔迹橡皮擦 在 WPF 里面,对于笔迹来说,应该放在 Stroke 类里面,而不是作为点的集合存储.在 Stroke 类里面将作为管理笔迹的类提供笔迹 ...
- GeoHash实现附近的人功能(如微信附近的人、共享单车附近的车辆、美团附近的商家)
如何查找当前点(118.818747°E,32.074497°N)附近500米的人? 这一类功能很常见(如微信附近的人.共享单车附近的车辆.美团附近的商家),那在java中是如何实 现的呢? 1 实现 ...
- vue引入一个单独的数据文件
1.新建一个address.js的文件 2.文件内const citys = { "北京市": ["东城区","西城区",& ...
- Process-与操作系统中的进程进行交互
1.Process介绍 在Java中,Process类是一个抽象类,它提供了与操作系统中的进程进行交互的方法.当你在Java程序中启动一个新的进程(例如,运行一个外部程序或脚本)时,JVM会创建一个P ...
- Oracle和达梦:根据外键名字查询表名
根据外键名字查询表名 select * from user_cons_columns cl where cl.constraint_name = '外键名';
- CF1800F Dasha and Nightmares
F.Dasha and Nightmares 题意:\(n\) 个字符串 \(s_i\),问有多少对不同的 \((i, j) \ (1 \le i \le j \le n)\),使得 \(s_i\) ...
- 数仓OLAP技术
数据应用,是真正体现数仓价值的部分,包括且又不局限于 数据可视化.BI.OLAP.即席查询,实时大屏,用户画像,推荐系统,数据分析,数据挖掘,人脸识别,风控反欺诈,ABtest等等 OLAP(On-L ...