-2

My code looks like this;

using (StreamWriter w = File.AppendText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "drivers/etc/hosts")))
{
    w.WriteLine("127.0.0.1 www.google.com");
}

I want get rid of duplicates in hosts file. How can I check if line exists and prevent appending it again?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Wiii
  • 3
  • 2

2 Answers2

1

You can use this little LINQ query to check if there's already a line:

bool exists = File.ReadLines(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "drivers/etc/hosts"))
    .Any(l => l == "127.0.0.1 www.google.com");
if(!exists)
    w.WriteLine("127.0.0.1 www.google.com");
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

May be a simple solution:
Just read all the text and check for the presence of your text. If not write to the file.

string texttowrite = "127.0.0.1 wwwgoogle.com";
string text = File.ReadAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "drivers/etc/hosts"), Encoding.UTF8);
if (!text.Contains(texttowrite))
{
    using (StreamWriter w = File.AppendText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "drivers/etc/hosts")))
    {
        w.WriteLine(texttowrite);
    }
}
Uthistran Selvaraj
  • 1,371
  • 1
  • 12
  • 31