• 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;    
        }    
    }  
  • 相关阅读:
    学习视屏
    Spring 和 MyBatis 环境整合
    struts2 多文件下载
    struts2的单文件下载
    很好的验证码
    Oracle 存储过程
    Oracle序列
    struts2 的多文件上传
    struts2的单文件上传
    NETBEAN 启动报错 CANNOT LOCATE JAVA INSTALLATION IN SPECIFIED JDKHOME的解决办法
  • 原文地址:https://www.cnblogs.com/wolbo/p/12310850.html
Copyright © 2020-2023  润新知