【问题标题】:Appending a line to a hosts file ONLY if it doesnt already exist [closed]仅在主机文件不存在时才将行附加到主机文件[关闭]
【发布时间】:2016-05-04 12:17:51
【问题描述】:

我的代码是这样的;

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

我想删除主机文件中的重复项。如何检查行是否存在并防止再次附加?

【问题讨论】:

  • 您想删除现有的重复项还是只是防止创建新的重复项?
  • 防止创建新的重复项

标签: c# streamwriter hosts


【解决方案1】:

可能是一个简单的解决方案:
只需阅读所有文本并检查您的文本是否存在。如果不写入文件。

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);
    }
}

【讨论】:

  • 效果很好,谢谢
【解决方案2】:

您可以使用这个小 LINQ 查询来检查是否已经有一行:

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");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多