Search code examples
c#textbox.net-4.5streamreader

How to check if a textbox has a line from a TXT File with C#


It's simple what I'm trying to do; when I click a button, my app should check if textBox1.Text has a line from a text file.

Note: I don't want to check if textbox has all the text file in it, just to see if it has a LINE from it.

I tried this with no success:

 private void acceptBtn_Click(object sender, EventArgs e)
    {
        StreamReader sr = new StreamReader(usersPath);
        string usersTXT = sr.ReadLine();
        if (user_txt.Text == usersTXT)
        {
            loginPanel.Visible = false;
        }
    }

Hope someone can help me. Thanks in Advance - CCB


Solution

  • string usersTXT = sr.ReadLine();
    

    Reads exactly one line. So you are only checking if you match the first line in the file.

    You want File.ReadALlLines (which also disposes the stream correctly, which you aren't):

    if (File.ReadAllLines(usersPath).Contains(user_txt.Text))
    {
    }
    

    That reads all the lines, enumerates them all checking if your line is in the collection. The only downside to this approach is that it always reads the entire file. If you want to only read until you find your input, you'll need to roll the read loop yourself. Do make sure to use the StreamReader in a using block if you take that route.

    You can also just use File.ReadLines (thanks @Selman22) to get the lazy enumeration version of this. I would go with this route personally.

    Implemenation that shows this at: http://referencesource.microsoft.com/#mscorlib/system/io/file.cs,675b2259e8706c26