码迷,mamicode.com
首页 > Windows程序 > 详细

c# 通过程序修改hosts文件

时间:2020-02-15 11:42:18      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:else   osi   win   cep   message   path   exception   host   str   

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 (!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;    
    }    
}  

 

c# 通过程序修改hosts文件

标签:else   osi   win   cep   message   path   exception   host   str   

原文地址:https://www.cnblogs.com/wolbo/p/12310850.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!