Search code examples
c#if-statementtextstreamwriter

Check if text exists in text file


I'm trying to figure out if the text URL that I get from current URL exists in 'linkx.txt', if it does then show a message, if it doesn't then write to text file. however, when I run this code program writes to text file twice before recognizing the text exists.

[working code]

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

Solution

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

    The main problem with your code is in this condition:

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

    You are looping through all the lines except the last one, which is likely the one you're searching for in this case.

    To resolve this, just remove the - 1 from your exit condition.


    With that being said, your code can be simplified greatly if you use the static ReadLines and AppendAllText methods of the File class:

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

    Then this method could be used in your code like:

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