2012-12-21 72 views
-1

在C#中使用hostfile我可以阻止网站,但我无法解除阻止它们。解锁特定网站

String path = @"C:\Windows\System32\drivers\etc\hosts"; 
StreamWriter sw = new StreamWriter(path, true); 
sitetoblock = "\r\n127.0.0.1\t" + txtException.Text; 
sw.Write(sitetoblock); 
sw.Close(); 

MessageBox.Show(txtException.Text + " is blocked", "BLOCKED"); 
lbWebsites.Items.Add(txtException.Text); 
txtException.Clear(); 

在这里,我需要一些帮助来解锁从列表框(lbWebsites)中选择的特定网站。有没有办法从主机文件中删除它们?我尝试了很多,并寻找其他解决方案,但每种解决方案都出现问题。

+3

当然,这是可能的。阅读文件并删除要取消阻止的IP并重写该文件。 “出现问题”甚至意味着什么? – PhoenixReborn

+0

出错了 - 写入权限? – fableal

+0

使用主机文件阻止网站并不是最好的方式。只需使用内置的windows-firewall来做到这一点;)想象一下你已经安装了本地代理的情况;) –

回答

1

您可以使用StreamReader将主机文件读取到string。然后,初始化StreamWriter的新实例,以将收集的内容写回到您想要解除阻止的网站之外。

string websiteToUnblock = "example.com"; //Initialize a new string of name websiteToUnblock as example.com 
StreamReader myReader = new StreamReader(@"C:\Windows\System32\drivers\etc\hosts"); //Initialize a new instance of StreamReader of name myReader to read the hosts file 
string myString = myReader.ReadToEnd().Replace(websiteToUnblock, ""); //Replace example.com from the content of the hosts file with an empty string 
myReader.Close(); //Close the StreamReader 

StreamWriter myWriter = new StreamWriter(@"C:\Windows\System32\drivers\etc\hosts"); //Initialize a new instance of StreamWriter to write to the hosts file; append is set to false as we will overwrite the file with myString 
myWriter.Write(myString); //Write myString to the file 
myWriter.Close(); //Close the StreamWriter 

谢谢,
我希望对您有所帮助:)

+0

非常感谢,它帮了我很多:) – user1913674

+0

@ user1913674我很高兴我能帮上忙。 [请注意,您可以将帖子标记为表示您已解决问题的答案](http://i.stack.imgur.com/uqJeW.png)。祝你有美好的一天:) –

+1

+1。考虑使用'using(){...}'代替'.Close',因为它安全('try' /'finally'已经为你写了 - 你的示例丢失了)并且更易于读取/验证。 –

3

您需要删除您写入的行来阻止网站。最有效的方法是读入hosts文件并重新写入。

顺便说一下,你的阻止网站的方法不会很有效。对于您的使用场景可能没有问题,但技术人员会知道要查看hosts文件。

+1

+1; Windows 8智能屏幕也积极地还原HOSTS文件的变化,因为它在攻击中被广泛使用。 – vcsjones

0

你可以这样做:

String path = @"C:\Windows\System32\drivers\etc\hosts"; 
System.IO.TextReader reader = new StreamReader(path); 
List<String> lines = new List<String>(); 
while((String line = reader.ReadLine()) != null) 
    lines.Add(line); 

然后你有你的主机的所有行文件在行列表中。之后,你可以搜索你想解锁,然后从列表中删除该网站,直到所需的网站已不再列表:

int index = 0; 
while(index != -1) 
{ 
    index = -1; 
    for(int i = 0; i< lines.Count(); i++) 
    { 
     if(lines[i].Contains(sitetounblock)) 
     { 
      index = i; 
      break; 
     } 
    } 
    if(index != -1) 
     lines.RemoveAt(i); 
} 

后,您这样做,只是清理列表转换为正常字符串:

String content = ""; 
foreach(String line in lines) 
{ 
    content += line + Environment.NewLine; 
} 

然后就内容写入文件中;)

写在我的头上,所以不能保证在具有没有错误:P