How do i change the hosts file in a windows program?

JRDH picture JRDH · Jun 29, 2011 · Viewed 23.9k times · Source

How would a program in C++/ C / C# program change the C:\Windows\System32\drivers\etc\hosts file content in windows? I know this sounds like phishing, honestly not.

Answer

Lotfi picture Lotfi · Jun 29, 2011

Hosts file has a very simple format where each line may contain "ip host" records

All you need is regular file appending :

using (StreamWriter w = File.AppendText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "drivers/etc/hosts")))
{
    w.WriteLine("123.123.123.123 FQDN");
}

Beware that by default you'll need elevated privileges to write to the hosts file...

In order to revert back, better take a backup of the file and restore it once you are done.