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), @"drivers\etc\hosts")))    
        {    
            w.WriteLine(entry);    
            return true;    
        }    
    }    
    catch (Exception ex)    
    {    
        Console.WriteLine(ex.Message);    
        return false;    
    }    
}  

 

posted @ 2020-02-15 10:45  wolbo  阅读(2105)  评论(0编辑  收藏  举报