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) 本篇会在这个解决方案基础上,继续修改. 一 ...
随机推荐
- 关于 Data Lake 的概念、架构与应用场景介绍
数据湖(Data Lake)概念介绍 什么是数据湖(Data Lake)? 数据湖的起源,应该追溯到2010年10月,由 Pentaho 的创始人兼 CTO, James Dixon 所提出,他提出的 ...
- Git 工具下载慢问题 & 图像化界面工具
Git 命令行淘宝镜像:git-for-windows Mirror (taobao.org) Git 图形客户端:Download – TortoiseGit – Windows Shell Int ...
- WPF 制作一个占用文件的测试工具
我在开发软件进行测试时,需要测试拖入的文件被占用时软件的行为,于是就做了一个文件占用工具,此工具可以将某个文件进行占用,以及获取某个文件被哪个进程占用 先给大家看一下效果: 以上是拖入文件到灰色部分, ...
- STM32定时器原理
一.简介 不同的芯片定时器的数量不同,STM32F10x中一共有11个定时器,其中2个高级控制定时器,4个普通定时器和2个基本定时器,以及2个看门狗定时器和1个系统嘀嗒定时器. 基本定时器:TIM6. ...
- vue通过input选取图片,jq的ajax向服务器上传img
<template> <div class=""> <!-- 选择后预览 --> <img v-if="im ...
- 259k+ Star!这是我见过最全的开发者技术学习路线!
大家好,我是 Java陈序员. 自从上班后,身体是一天不如一天了,也很少有时间可以去学习新技术了.程序员如果技术跟不上,很容易就被淘汰. 而碎片化的学习效率又不高,往往今天学了,明天就忘了.有时候更是 ...
- Solution Set - NOI级别真题选做
[NOI2007] 社交网络 Link&Submission. key:Floyd Floyd求出任意两点间最短路,以及最短路的条数.求点 \(k\) 的答案时枚举所有点对 \(i,j\),若 ...
- 茴香豆 RAG 平台实操-书生浦语大模型实战营第二期第3节作业
书生浦语大模型实战营第二期第3节作业 本页面包括实战营第二期第三节作业的全部操作步骤.如果需要知道RAG相关知识请访问学习笔记. 作业要求 基础作业 在茴香豆 Web 版中创建自己领域的知识问答助手 ...
- ERROR: Error installing mysql2: ERROR: Failed to build gem native extension [@Ubuntu 15.04]
参考文章: https://blog.csdn.net/a60919820/article/details/101847890 安装mysql 参考:https://www.cnblogs.com/h ...
- go-admin 视频教程
https://cloud.189.cn/t/6JJ3uqreqyai (访问码:2xn5) 感谢 熊猫 同学 整理 失效了可以去B站看 https://www.bilibili.com/video/ ...