Reputation: 2913
I'm making a program to add/remove entries to the Windows hosts file. So far it works fine except sometimes when I remove an item using my form, it will clear the entire hosts file, leaving nothing.
Here is my code:
public void removeFromHosts(String key)
{
MessageBox.Show(key);
if (key != "" || key != " ")
{
String[] strings = new String[1000];
String all = File.ReadAllText(hostFile);
strings = all.Split('\n');
StreamWriter writer = new StreamWriter(hostFile);
foreach (String s in strings)
{
if (s != "255.255.255.255 " + key + " #Blocked by MyProgram")
{
writer.Write(s);
}
else
{
textBox1.Text += s;
}
}
writer.Close();
blockurls.SelectedItems[0].Remove();
MessageBox.Show("URL Successfully removed");
}
else
{
MessageBox.Show("Empty");
}
}
I'm basically checking each line in the textfile to see if it contains the url, if it doesn't contain the url then write that line to the file. What could be causing it to wipe the entire file?
Upvotes: 0
Views: 365
Reputation: 2913
Fixed using this code:
public void removeFromHosts(String key) {
ArrayList strings = new ArrayList();
StreamReader reader = new StreamReader(hostFile);
while (reader.Peek() > -1)
{
strings.Add(reader.ReadLine());
}
reader.Close();
StreamWriter writer = new StreamWriter(hostFile);
foreach (String s in strings)
{
if (!s.Contains("255.255.255.255 " + key + " #Blocked by Parental Care"))
{
writer.Write(s + "\n");
}
}
writer.Close();
blockurls.SelectedItems[0].Remove();
MessageBox.Show("URL Successfully removed");
}
Upvotes: 0
Reputation: 66122
It seems to me that you are checking if the entry "contains" the value entered. However, this would be dangerous. In the documentation it states that if you pass it an empty string, contains will always return true. If the key is empty string, all lines will be removed. Also, If your key is something like "a" then all entries with an a will be be removed. Perhaps you should be checking if the string equals the key, or do some more complex kind of check. I assume you're entering the hostname as the key, pick apart the line, and ensure that the host name matches the value in the key.
You could probably fix your code by replacing the contains with something like
s = "255.255.255.255 " + key
Or maybe
Regex.IsMatch(s,"^255\.255\.255\.255\s+" + Regex.Escape(key) + "\s*$")
Upvotes: 2