Introduction
Sometimes it becomes ridiculous to edit your hosts file for just adding a list of websites that you want to block on your machine .... for making a solution and making
it easier to do this I have created a program that can edit your hosts file.
Background
For blocking any site you need to add code like 127.0.0.1 http://www.facebook.com at the end of the file and that becomes a ridiculous task
to add it whenever we want to block a site and remove it when we want to remove it....
Using the code
We have three buttons: button1 for adding the required blocking site information into the host file and button 2 for removing added code ... and button
3 for exitting from the application, like this:
using System.IO;
private void button1_Click(object sender, EventArgs e)
{
using (StreamWriter tw = File.AppendText("C:\\Windows\\System32\\drivers\\etc\\hosts"))
{
tw.WriteLine("127.0.0.1 login.facebook.com");
tw.WriteLine("127.0.0.1 www.facebook.com");
tw.WriteLine("127.0.0.1 blog.facebook.com");
tw.WriteLine("127.0.0.1 apps.facebook.com");
tw.WriteLine("");
tw.Close();
}
}
private void button2_Click(object sender, EventArgs e)
{
TextWriter tw = new StreamWriter("C:\\Windows\\System32\\drivers\\etc\\hosts");
tw.WriteLine("# Copyright (c) 1993-2009 Microsoft Corp.");
tw.WriteLine("#");
tw.WriteLine("# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.");
tw.WriteLine("#");
tw.WriteLine("# This file contains the mappings of IP addresses to host names. Each");
tw.WriteLine("# entry should be kept on an individual line. The IP address should");
tw.WriteLine("# be placed in the first column followed by the corresponding host name.");
tw.WriteLine("# The IP address and the host name should be separated by at least one");
tw.WriteLine("# space.");
tw.WriteLine("#");
tw.WriteLine("# Additionally, comments (such as these) may be inserted on individual");
tw.WriteLine("# lines or following the machine name denoted by a '#' symbol.");
tw.WriteLine("#");
tw.WriteLine("# For example:");
tw.WriteLine("#");
tw.WriteLine("# 102.54.94.97 rhino.acme.com # source server");
tw.WriteLine("# 38.25.63.10 x.acme.com # x client host");
tw.WriteLine("# localhost name resolution is handled within DNS itself.");
tw.WriteLine("# 127.0.0.1 localhost");
tw.WriteLine("# ::1 localhost");
tw.WriteLine("");
tw.Close();
tw.Dispose();
}
private void button3_Click(object sender, EventArgs e)
{
Application.Exit();
}
Points of Interest
We need to edit file at C:\Windows\System32\drivers\etc\hosts and the host file doesn't have any extension.