Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search specific string and return whole line

What I would like to do is find all instances of a string in a text file, then add the full lines containing the said string to an array.

For example:

eng    GB    English
lir    LR    Liberian Creole English
mao    NZ    Maori

Searching eng, for example, must add the first two lines to the array, including of course the many more instances of 'eng' in the file.

How can this be done, using a text file input and C#?

like image 308
apophis Avatar asked Jun 24 '11 10:06

apophis


1 Answers

you can use TextReader to read each line and search for it, if you find what u want, then add that line into string array

List<string> found = new List<string>();
string line;
using(StreamReader file =  new StreamReader("c:\\test.txt"))
{
   while((line = file.ReadLine()) != null)
   {
      if(line.Contains("eng"))
      {
         found.Add(line);
      }
   }
}

or you can use yield return to return enumurable

like image 145
Bek Raupov Avatar answered Sep 18 '22 22:09

Bek Raupov