0

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;
                        }
                    }
                }
            }
        }
3
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by iconoclazt
0

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

Thanks that help and worked

Edited by m_wylie85: n/a

-1
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 by iconoclazt: n/a

Votes + 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.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.