Hi all i have writen a bit of code here to read a line of text from a text file and display it depending on what the user searches for which is taken from a text box.

but it will only read one line it will not display all the records that have the word input from the text box what am missing.

private void btnSearch_Click(object sender, EventArgs e)
        {
            {
                string searchText = (txtSearchBirthMonth.Text);
                string file = @"C:\Users\michael\Documents\data.txt ";//path to text file 
                StreamReader reader = new StreamReader(file); string line = null;
                foreach (string record in reader.ReadLine().Split('|'))
                {
                    while ((line = reader.ReadLine()) != null)
                    {
                        if (Regex.IsMatch(line, searchText, RegexOptions.IgnoreCase))
                        {
                            rtbRecord.Text = line;
                        }
                    }
                }
            }
        }

I see two potential issues with your code:

// first call to ReadLine() advances the stream
foreach (string record in reader.ReadLine().Split('|'))
{
  // first time will read the second line because of first call
  while ((line = reader.ReadLine()) != null)
  {
    if (Regex.IsMatch(line, searchText, RegexOptions.IgnoreCase))
    {
      // the text here will be overwritten on each pass, try += instead
      rtbRecord.Text = line;
    }
  }
}
public string GrepLineFromFile(string path, string pattern)
{
    if (File.Exists(path))
    {
        foreach (string line in File.ReadAllLines(path))
        {
            if (line.Contains(pattern))
            {
                return (line); 
            }
        }
    }
    else
    {
        Console.WriteLine("..file does not exist");
    }

    return (string.Empty);
}

Edited 5 Years Ago by iconoclazt: n/a

Comments
You should try to help people arrive at the answer, not just hand-feed them code without explanation
This question has already been answered. Start a new discussion instead.