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

 

原文地址:http://www.cnblogs.com/runliuv/p/16915213.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性