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

Check if text exists in text file

我正在尝试确定我从当前 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);
}

它比你得到的要简单得多。如果你只有一个字符串数组,你可以使用 Array.Contains.

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

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

"when I run this code program writes to text file twice before recognizing the text exists"

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

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

您正在遍历所有行,除了最后一行,这可能是您在本例中要搜索的行。

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


话虽如此,如果您使用 File class:[=18= 的静态 ReadLinesAppendAllText 方法,您的代码可以大大简化]

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