JRDH
JRDH

Reputation: 107

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

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.

Upvotes: 9

Views: 28700

Answers (6)

Jishnu U Nair
Jishnu U Nair

Reputation: 520

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.

Upvotes: 2

Lotfi
Lotfi

Reputation: 1205

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.

Upvotes: 15

Kristian Williams
Kristian Williams

Reputation: 2343

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.

Upvotes: 4

David Anderson
David Anderson

Reputation: 13670

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

Upvotes: 14

Eric Petroelje
Eric Petroelje

Reputation: 60498

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.

Upvotes: 9

driis
driis

Reputation: 164281

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.

Upvotes: 4

Related Questions