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

6

9

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.

Vespasian answered 29/6, 2011 at 21:2 Comment(2)
What does "His promittion" means? Also... why would you want to do that?Melchizedek
you wouldnt want to do that, read about using DNS for resolving host namesNagey
T
15

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.

Tatter answered 29/6, 2011 at 21:12 Comment(1)
How to remove entries when needed?Kev
M
14

First, you should request for administrative permission from the user. You can do this through your Program class in your application. The below code will request the user for administrative access, the user then has the option to allow or deny it. If they deny it, this example does not run the application.

Once your application is run in administrative mode, its plain text with simple formatting. You do not even need all the Microsoft comments included in the file, and simple string parsing will do just fine. The comments by MSFT in the HOSTS file are all the documentation you really need as far as the HOSTS file itself goes.

namespace Setup {
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows.Forms;
    using Setup.Forms;
    using System.Security.Principal;
    using System.Diagnostics;

    static class Program {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main() {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
            bool administrativeMode = principal.IsInRole(WindowsBuiltInRole.Administrator);

            if (!administrativeMode) {
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.Verb = "runas";
                startInfo.FileName = Application.ExecutablePath;
                try {
                    Process.Start(startInfo);
                }
                catch {
                    return;
                }
                return;
            }

            Application.Run(new ShellForm());
        }
    }
}
Mcgurn answered 29/6, 2011 at 21:29 Comment(5)
Note that by copying your code here it's effectively released under CC-Wiki. The copyright block is ineffective. Not sure if you want to remove the copyright block or the whole answer....Oldtimer
I own DCOM Productions and I just copied the entire contents of the file for a quick answer. Either way it doesn't matter, just using it to give him an approach to his question. If I didn't want him to use the code I wouldn't have posted at all. ;)Mcgurn
Okay. :) Just didn't want you to inadvertently release your IP under a less restrictive license than you intended.Oldtimer
Ah, no biggy. The project it came from is a framework I've been writing for a few years now and will probably go open source by the end of JulyMcgurn
Can you edit your answer to remove the notification? Its just drawing unnecessary attention (mod flags and meta questions)Caruncle
J
9

The file is usually located at C:\Windows\System32\drivers\etc\hosts. Rather than hard coding the C:\Windows part though, you should use Environment.GetEnvironmentVariable("SystemRoot") to safely determine the system root directory.

Otherwise you can write to it like any other file, assuming you have the proper permissions.

Jonquil answered 29/6, 2011 at 21:10 Comment(1)
Environment.GetFolderPath(Environment.SpecialFolder.System) is even better.Collayer
D
4

The hosts file is just plain text. The format is each line contains the IP and the hostname that IP should resolve to, separated by whitespace. # denotes a comment.

Example:

# This is a comment-
127.0.0.1    mysuperhost.com

The file is located here: C:\Windows\system32\drivers\etc\hosts. You will (with good reason), need administrator privileges to write to it.

Dejong answered 29/6, 2011 at 21:7 Comment(0)
F
3

The most accurate way of finding the HOSTS file location is to read the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DataBasePath registry key, and appending hosts to the end.

This will always point to the correct location for the current machine configuration and works for all Windows NT based platforms since Windows NT 4.0.

Footlight answered 20/6, 2013 at 8:52 Comment(2)
Unfortunately this does not seem to be the case with the more modern operating systems. Specifically on Windows 7, if you change the DataBasePath value, it will not use the new location.Verdie
Whether changing the value affects it (or if Microsoft even supports doing so) isn't an issue. The question was how to edit the current hosts file, I simply gave the most reliable way to find said file. (Assuming you've not been messing in the registry.) For the given purpose, this method is valid from Windows NT 4.0 up to and including Windows 8.1 Update 1Footlight
S
2

As a guy who struggled with this problem, easy way out, copy the hosts file to temp folder, modify it and copy it back with overwrite. Running the application as admin, will be the best.

Salinger answered 12/8, 2015 at 8:41 Comment(1)
... This answer is like going onto a car repair forum and telling the OP, "The easy way out is to start walking to your destinations instead of fixing your car."Eous

© 2022 - 2024 — McMap. All rights reserved.