Programming out of need – HOSTS File Editor

I work within the realm of  QA testing and have to constantly edit my Windows hosts file to redirect to other servers during the course of an average day and although I had a few batch files to run, or could run Powershell, I wished I had a tool that I could use to do it quicker. I looked around the net and didn’t find anything useful, surprisingly.

I thought about it for a few weeks and then just decided to dive in and take a stab at it so at home on my home PC, because I don’t want any conflicts doing this on a work machine, I started learning C# in Visual Studio. All I was armed with really was a plain text file with redirects that I could copy and paste into the hosts file depending on what I needed to accomplish test wise and a couple batch files I used to previously do it.

Example:

##=========WORDPRESS========
## redirect to wp0 on domain
#111.111.111.111 http://www.domain.com secure.domain.com

##===========VARN===========
## redirect to v0 on domain
#111.111.111.111 v0.ourdomain.com

## redirect to vs on domain
#111.111.111.111 http://www.domain.com secure.domain.com

##======== TEST SERVER ========
## redirect to test on domain
#111.111.11.11 test.domain.com

At first I thought of doing an app where I could select each server from a combobox and then launch Notepad as Admin to copy and then save the info, then it was a combobox with form button events and lengthy if else if statement to write the server info to the hosts file. It was certainly worse code for wear for sure.

Some source snippets from that messy thing:


private void Form1_Load(object sender, EventArgs e)

{
string v0string = "v0.domain.com";
string vstagestring = "vs.domain.com";
string wp0string = "wp0.domain.com";
string test1string = "test.domain.com";

comboBox1.Items.Add(v0string);
comboBox1.Items.Add(vstagestring);
comboBox1.Items.Add(wp0string);
comboBox1.Items.Add(test1string);

}
//
//
//Another excerpt of my messy code
//
string selected = (string)comboBox1.SelectedItem;

if (selected == "v0string")

{
string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
StringBuilder sb = new StringBuilder();

sb.AppendLine("#redirect to v0.domain.com");
sb.AppendLine("111.111.111.111 www.domain.com domain.com secure.domain.com");
sb.AppendLine();
using (StreamWriter outfile = new StreamWriter(mydocpath + @"\SampleHostsFile.txt")) //test path
{
await outfile.WriteAsync(sb.ToString());
toolStripStatusLabel1.Text = "HOSTS file redirected to v0";
}
}
else if (selected == "vs.domain.com")
{
string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
StringBuilder sb = new StringBuilder();
sb.AppendLine("#redirect to vs.domain.com");
sb.AppendLine("#54.241.35.155 www.domain.com domain.com #secure.domain.com");
sb.AppendLine();
using (StreamWriter outfile = new StreamWriter(mydocpath + @"\SampleHostsFile.txt"))
{
await outfile.WriteAsync(sb.ToString());
toolStripStatusLabel1.Text = "HOSTS file redirected to vs";
}
}

I took a step back to reanalyze my need and through several iterations came up with a host file manager that worked for me. In a nutshell it will read in my hosts data file (hostsdata.txt) into a checkedbox component, allowing me to check what I want and then write those items to my systems hosts file.

I made some additions to the tool such as starting with elevated admin privileges which are needed in order to write to the hosts file, the ability to reset the hosts file to default commented text, a way to perform functions similar to ipconfig /release, /renew and /flushdns using WMI and added the small editor t
o the tool to allow me to edit the hostsdata.txt file for new or changed redirect information.

mainapp_sm

Main Application

mainapp_editor_sm

Editor Window

As you can see in the screenshots, my data file entries have the hash tags which the hosts file recognizes as commenting. The procedure / block of code for writing the information to the hosts file will strip that forward hash tag (the #) so that it is written to file as uncommented already.

However, as you can tell in the screenshot of the main application, there are some checkboxes that do not contain a display value and I haven’t added any code for processing that so I just catch the exception to get on with my day – I just don’t click on the blank entries. The code below is what I use for the button click event to write to the hosts file:


{
StringBuilder sb = new StringBuilder();

if (checkedListBox1.CheckedItems.Count != 0)

{
// Loop through for all checked items
string s = "";
for (int x = 0; x <= checkedListBox1.CheckedItems.Count - 1; x++)

try
{
//uncomment the # and wrap next item to the next line
s = s + checkedListBox1.CheckedItems[x].ToString().Remove(0, 1) + "\r\n";
}
// add an if statement to check for null string or null
//checkedlistbox item (if value is empty then do something)
catch (Exception ex)
{
Console.WriteLine(ex);
MessageBox.Show(ex + "Oh No!!!");
}
sb.AppendLine(s);  // checked items to string here
sb.AppendLine();   // add a blank line
string myhostspath = (Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\drivers\\etc\\hosts");
using (StreamWriter outfile = new StreamWriter(myhostspath))
{
await outfile.WriteAsync(sb.ToString());   // write contents to file
}
}

//############################## IP Code ################################
[DllImport("dnsapi.dll", EntryPoint = "DnsFlushResolverCache")]
private static extern UInt32 DnsFlushResolverCache();
public static void FlushDNSCache() //flush dns cache
{
UInt32 result = DnsFlushResolverCache();
//    MessageBox.Show("Done");
}

//similar to ipconfig release
private void button3_Click(object sender, EventArgs e)
{
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
objMO.InvokeMethod("ReleaseDHCPLease", null, null);
}
CommitLabel.Text = "IP released";     // Add to statusbar
}

//Similar to ipconfig renew<br />        private void button4_Click(object sender, EventArgs e)
{
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
objMO.InvokeMethod("RenewDHCPLease", null, null);
}
CommitLabel.Text = "IP renewed";     // Add to statusbar
}

//Flush DNS
private void FlushDNS_Click(object sender, EventArgs e)
{
FlushDNSCache();
CommitLabel.Text = "DNS Flushed";     // Add to statusbar
}

In any regard, I am not a professional programmer and essentially just dove in on this because I had a need and hated the way I currently had to deal with modifying the hosts file. I didn’t find any tools online so I created this app to use. I still tweak and refine this tool a little but take it as a tool that was just something whipped up to get ‘er done. Any comments are welcomed here or to my email or if you have trouble downloading the file for some reason – email at stevegossett[[at]]outlook.com.

Host Editor Tool Download

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s