How to unblock website which is blocked, using C#?
Question
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");
Solution
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 :
- read the host file
- find the site url by regex
- delete the line
- save the file.
OTHER TIPS
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());
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)));
Just replace hosts file to original.
if you want original hosts file then i can send you.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow