Last active
March 19, 2017 15:45
-
-
Save JKamsker/ef2802b57e09d78044d1cb1e65d34a3c to your computer and use it in GitHub Desktop.
Patches Hosts file entities (add & update )
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static void PatchHosts() | |
{ | |
string HostFileLocation = @"C:\Windows\System32\drivers\etc\hosts"; | |
Regex rgxHosts = new Regex(@"\b((\d{1,3}\.){3}\d{1,3})\b[ ]+([a-zA-Z0-9.]+)", RegexOptions.ECMAScript | RegexOptions.Compiled); | |
List<String> HostsFile = new List<string>(File.ReadAllLines(HostFileLocation)); | |
//Parse Entities into an easy <domain,ip> list | |
var myDict = HostsFile | |
.Select(m => m.Split("#")[0]).Where(m => m != "") | |
.Select(m => rgxHosts.Match(m)) | |
.Where(m => m.Groups.Count >= 3) | |
.ToDictionary(m => m.Groups[3].Value, m => m.Groups[1].Value); | |
myDict["ffasx.de"] = "127.0.0.1"; | |
//Replace already existing entities | |
for (int i = 0; i < HostsFile.Count; i++) | |
{ | |
for (int a = myDict.Count - 1; a >= 0; a--) | |
{ | |
var item = myDict.ElementAt(a); | |
if (HostsFile[i].Contains(item.Key)) | |
{ | |
HostsFile[i] = item.Value + " " + item.Key; | |
myDict.Remove(item.Key); | |
} | |
} | |
} | |
//Add remaining Items which werent in the dictionary in the first place | |
foreach (var item in myDict) | |
{ | |
HostsFile.Add(item.Value + " " + item.Key); | |
} | |
//Save changes | |
File.WriteAllLines(HostFileLocation, HostsFile); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment