zoukankan      html  css  js  c++  java
  • c# 通过程序修改hosts文件

    1 根据ip替换

    var OSInfo = Environment.OSVersion;
    string pathpart = "hosts";
    if (OSInfo.Platform == PlatformID.Win32NT)
    {
        //is windows NT
        pathpart = "system32\drivers\etc\hosts";
    }
    string hostfile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), pathpart);
    
    const string tales = "123.123.123.123 download.talesrunner.com";

    if (!((IList)File.ReadAllLines(hostfile)).Contains(tales)) { File.AppendAllLines(hostfile, new String[] { tales }); }

    2 根据域名替换

     const string tales = "123.123.123.123 download.talesrunner.com";
        string[] lines = File.ReadAllLines(hostfile);
    
        if (lines.Any(s => s.Contains("download.talesrunner.com")))
        {
            for (int i = 0; i < lines.Length; i++)
            {
                 if (lines[i].Contains("download.talesrunner.com"))
                     lines[i] = tales;
            }
            File.WriteAllLines(hostfile, lines);
        }
        else if (!lines.Contains(tales))
        {
            File.AppendAllLines(hostfile, new String[] { tales });
        }

    3 直接追加

    public static bool ModifyHostsFile(string entry)    
    {    
        try    
        {    
            using (StreamWriter w = File.AppendText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), @"driversetchosts")))    
            {    
                w.WriteLine(entry);    
                return true;    
            }    
        }    
        catch (Exception ex)    
        {    
            Console.WriteLine(ex.Message);    
            return false;    
        }    
    }  
  • 相关阅读:
    ECMAScript 6 基础入门
    软件历史版本存档及下载
    arduino 编程基础
    生活中的实验 —— 家庭电路
    电子元件 —— 继电器
    电与磁 —— 电磁铁
    windows cmd 命令行 —— 进程与服务
    计算机硬件、摄影设备、物质、材料英语
    DHCP服务器备份、还原、迁移
    SVN同步
  • 原文地址:https://www.cnblogs.com/wolbo/p/12310850.html
Copyright © 2011-2022 走看看