Programmatically Modify Windows Hosts File using C#

There may be certain scenarios like code setup or creating IIS web sites,where we need to add an entry to windows hosts file. We will understand how to modify hosts file using C# Console application. Create a Visual Studio 2010 Console application and name it HostsModify and add the following method: 
  1. public static bool ModifyHostsFile(string entry)    
  2. {    
  3.     try    
  4.     {    
  5.         using (StreamWriter w = File.AppendText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), @"drivers\etc\hosts")))    
  6.         {    
  7.             w.WriteLine(entry);    
  8.             return true;    
  9.         }    
  10.     }    
  11.     catch (Exception ex)    
  12.     {    
  13.         Console.WriteLine(ex.Message);    
  14.         return false;    
  15.     }    
  16. }  
In above method, we are getting path of Windows hosts file and writing the entry passed to the method into it. Let's call this method from Main method and run the application:
  1. static void Main(string[] args)    
  2. {    
  3.     Console.WriteLine("Please enter network details to be added in Windows hosts file:");    
  4.     string entries = Console.ReadLine();    
  5.     if (ModifyHostsFile(entries))    
  6.     {    
  7.         Console.WriteLine("Entry added successfully....");    
  8.         Console.ReadLine();    
  9.     }    
  10. }  
cmd

We can further extend this application by providing Delete\Modify hosts file options.
Ebook Download
View all
Learn
View all