tags:

views:

1527

answers:

4

This is some code to unblock any website from listview, but now I want to unblock a website which has previously been blocked. How can I do this?

String path = @"C:\Windows\System32\drivers\etc\hosts";
StreamWriter sw = new StreamWriter(path, true);
String sitetoblock = "\n 127.0.0.1 http://"+listView1.SelectedItems[0].Text+"";
sw.Write(sitetoblock);
sw.Close();
MessageBox.Show(listView1.SelectedItems[0].Text " blocked");
+7  A: 

It's not the right way to block a website, but here is the way to 'unblock' a site that is 'blocked' by your code is simply :

  1. read the host file
  2. find the site url by regex
  3. delete the line
  4. save the file.
Canavar
+3  A: 

You can use System.IO.File's ReadAllLines & WriteAllLines functions and just strip out the line you want to remove

        string path = @"C:\Windows\System32\drivers\etc\hosts";

        string [] lineArray = System.IO.File.ReadAllLines(path);

        List<string> lines = blah.ToList();

        string sitetoUNblock = string.Format("127.0.0.1 http://{0}", listView1.SelectedItems[0].Text);

        lines.Remove(sitetoUNblock);

        System.IO.File.WriteAllLines(path, lines.ToArray());
Eoin Campbell
+1  A: 

Code Golf

string path = @"C:\Windows\System32\drivers\etc\hosts";
string itemText = listView1.SelectedItems[0].Text;
File.WriteAllLines(path, File.ReadAllLines(path).Where(site=>site!=string.Format("127.0.0.1 http://{0}", itemText)));
Jacob Adams
+1  A: 

Just replace hosts file to original.

if you want original hosts file then i can send you.

That would 'unblock' *every* site, not *a* site.
TM