none
How to Search keyword in whole text file? using C#

    Question

  • Hi, i am very new to programming world and now i have been assign to work on for develop new application using C# code ( Microsoft visual c# 2010 express). I stuck on how to search certain keyword in the text file that read from top to bottom of the file. Then, if the keyword that i search is found(can be one or more), i want to copy the 2line above and 2line below the keyword to other text file.

    i ve tried sourcecode from Vin Jin:

    private void search(String temp)
      {
       String[] lines = File.ReadAllLines("aa.txt");
       for (int i = 0; i < lines.Length; i++)
       {
        if (temp.Equals(lines[i]))
        {
         FileStream fs = File.Create("bb.txt");
         StreamWriter sw = new StreamWriter(fs);
         for (int j = i - 2; j <= i + 2; j++)
         {    
          sw.WriteLine(lines[j]);
         }
         sw.Close();
         fs.Close();
         break;
        }
       }
      }

    =========================

    It work perfect when in my text contain only one keyword that i want to search. But, my problem come when in my text file contain more then one for the keyword that i want to search. My question is, how i gonna search the keyword in my whole text files??? and then copy them in other file (bb.txt).

    Please, help me out... Thanks in advance



    Wednesday, November 03, 2010 1:04 AM

Answers

  • Hi,

    Do you mean you have more than one keywords and every keywords if found should copy  the 2line above and 2line below the keyword to other text file.?

    If so , you can try that:

    private void search(String[] keys)
        {
          String[] lines = File.ReadAllLines("aa.txt");
          FileStream fs = File.Create("bb.txt");
          StreamWriter sw = new StreamWriter(fs);
          for (int i = 0; i < lines.Length; i++)
          {
            if (keys.Contains(lines[i]))
            {
              for (int j = ((i - 2) > 0 ? i - 2 : 0); j <= i + 2 && j < lines.Length; j++)
              {
                sw.WriteLine(lines[j]);
              }
            }
          }
          sw.Close();
          fs.Close();
        }
    Hope helps. I test it in my computer, it works well.

    Vin  Jin

    • Marked as answer by Jing0Moderator Tuesday, November 09, 2010 9:14 AM
    Wednesday, November 03, 2010 7:37 AM