Leviathan
Leviathan

Reputation: 31

How to replace the hosts file on C#

I just want to know how can I completely replace the user's hosts file with another one? Note: I wana give the user just my .exe compiled file(With my own hosts file attached to it) and after running the exe file the user's hosts file should be replaced with my own hosts file I attached to my exe file.

Upvotes: 0

Views: 1337

Answers (1)

Elkhan Ibrahimov
Elkhan Ibrahimov

Reputation: 234

Simple way, you can use IO library.

        string path = "system32\\drivers\\etc\\hosts";
        string hostfile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), path);

        const string checkIP = "127.0.0.1 localhost";
        if (!File.ReadAllLines(hostfile).Contains(checkIP))
            File.AppendAllLines(hostfile, new string[] {checkIP});

Do not forget, your program must run with administrator privileges, otherwise you will get an UnauthorizedAccessException exception.

Upvotes: 1

Related Questions