检查文本文件中是否存在文本

时间:2018-08-29 22:19:42

标签: c# if-statement text streamwriter

我试图确定从当前URL获得的文本URL是否存在于“ linkx.txt”中,如果确实显示一条消息,然后不写入文本文件。但是,当我运行此代码时,程序会在识别文本存在之前两次写入文本文件。

[工作代码]

  protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    string linkx = @"Desktop\linkx.txt";
    string url = "";
    if (keyData == Keys.F1) { Application.Exit(); return true; }
    else if (keyData == Keys.F2) { url = webBrowser1.Url.AbsoluteUri; return true; }

    using (StreamReader sr = File.OpenText(linkx))
    {
        string texxt = url;
        string[] lines = File.ReadAllLines(linkx);
        bool matched = false;
        for (int x = 0; x < lines.Length; x++)
        {
            if (texxt == lines[x])
            {
                sr.Close();
                MessageBox.Show("there is a match");
                matched = true;
            }
        }
        if (!matched)
        {
            sr.Close();
            using (StreamWriter wriite = File.AppendText(linkx))
            {
                wriite.WriteLine(url);
                MessageBox.Show("url copied!");
                return true;    // indicate that you handled this keystroke
            }
        }
    }
    // Call the base class
    return base.ProcessCmdKey(ref msg, keyData);
}

2 个答案:

答案 0 :(得分:2)

比您所拥有的要简单得多。如果您只有一个字符串数组,则可以使用Array.Contains

var lines = File.ReadAllLines("links.txt");

if (!lines.Contains("google.com")) {
  File.AppendAllText("links.txt", "google.com");
}

答案 1 :(得分:2)

  

“当我运行此代码程序时,在确认文本存在之前两次写入文本文件”

您的代码的主要问题是在这种情况下:

for (int x = 0; x < lines.Length - 1; x++)

您正在遍历所有行,最后一行除外,在这种情况下,这很可能是您要搜索的行。

要解决此问题,只需从退出条件中删除- 1


话虽如此,如果您使用ReadLines类的静态AppendAllTextFile方法,则可以大大简化代码:

/// <summary>
/// Searches the specified file for the url and adds it if it doesn't exist.
/// If the specified file does not exist, it will be created.
/// </summary>
/// <param name="filePath">The path to the file to query.</param>
/// <param name="url">The url to search for and add to the file.</param>
/// <returns>True if the url was added, otherwise false.</returns>
protected static bool AddUrlIfNotExist(string filePath, string url)
{
    if (!File.Exists(filePath)) File.Create(filePath).Close();

    if (!File.ReadLines(filePath).Any(line => line.Contains(url)))
    {
        File.AppendAllText(filePath, url);
        return true;
    }

    return false;
}

然后可以在您的代码中使用此方法,例如:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == Keys.F1) { Application.Exit(); return true; }

    if (keyData == Keys.F2)
    {
        if (AddUrlIfNotExist("linkx.txt", webBrowser1.Url.AbsoluteUri))
        {
            MessageBox.Show("url copied!");
        }
        else
        {
            MessageBox.Show("there is a match");
        }
    }

    // Call the base class
    return base.ProcessCmdKey(ref msg, keyData);
}