c# how to read same line from multiple files after a search from 1 of the files?

464 Views Asked by At

This is something similar from what I am working on, I have to do the 3 files at the same time sequentially, and when string is found it displays the data from that line of each file. My problem so far is that it does not read data from the second and third files correctly, it reads only the first line. My second problem, I am trying to use

String.Compare(string1, searchBox, true) 

but I am not really sure on where to put it so the search ignores spaces (trim) or capital letters during search. The code:

    string string1, string2, string3, searchBox;

    StreamReader file1, file2, file3;

    file1 = File.OpenText("data1.dat");
    file2 = File.OpenText("data2.dat");
    file3 = File.OpenText("data3.dat");

    string1 = file1.ReadLine();
    string2 = file2.ReadLine();
    string3 = file3.ReadLine();

    searchBox = searchTxtBox.Text.Trim();

    while ((string1 = file1.ReadLine()) != null)
    {
          if (string1.Contains(searchBox))
          {
           infoListBox.Items.Add(string1 + "====" + string2 + "====" + string3);
           break;
          }
    }

file1.Close();
file2.Close();
file3.Close();
1

There are 1 best solutions below

7
On BEST ANSWER
string string1, string2, string3, searchBox;

StreamReader file1, file2, file3;

file1 = File.OpenText("data1.dat");
file2 = File.OpenText("data2.dat");
file3 = File.OpenText("data3.dat");

searchBox = searchTxtBox.Text.Trim();

while ((string1 = file1.ReadLine()) != null
    && (string2 = file2.ReadLine()) != null 
    && (string3 = file3.ReadLine()) != null)
{
      if (string1.IndexOf(searchBox, StringComparison.CurrentCultureIgnoreCase) >= 0)
      {
       infoListBox.Items.Add(string1 + "====" + string2 + "====" + string3);
       break;
      }
}

file1.Close();
file2.Close();
file3.Close();