-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)中选择的特定站点。有没有办法从主机文件中删除它们?我尝试了很多并查看了其他解决方案,但每个解决方案都出现了问题。

4

3 回答 3

3

您需要删除您为阻止该站点而编写的行。最有效的方法是读入hosts文件,然后再写。

顺便说一句,您阻止网站的方法不会非常有效。对于您的使用场景可能没问题,但稍微有点技术含量的人会知道查看 hosts 文件。

于 2012-12-21T17:57:22.920 回答
1

您可以使用 aStreamReader将 hosts 文件读入string. 然后,初始化 a 的新实例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

谢谢,
我希望你觉得这有帮助:)

于 2012-12-21T18:01:21.347 回答
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

于 2012-12-21T18:10:08.373 回答