c# 通过程序修改hosts文件
2021-03-20 05:24
标签:else osi win cep message path exception host str 1 根据ip替换 2 根据域名替换 3 直接追加 c# 通过程序修改hosts文件 标签:else osi win cep message path exception host str 原文地址:https://www.cnblogs.com/wolbo/p/12310850.htmlvar 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 });
}
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 )
{
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 });
}
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;
}
}