+92 332 4229 857 99ProjectIdeas@Gmail.com

Search A Word In File (C#.net)


The following code shows you how to search a word in file, a function SearchWord() takes two parameters first the file path and the second is the word to be search in file.
Reading a file line by line and splitting at every space now all the words excluding of space are in new string array and with the loop, searching a word in this new array where it equals count plus by one.


 
using System.IO;

public void SearchWord(string filePath, string searchString)
{

      TextReader tr = File.OpenText(filePath);
           
      int word = 0;

      string line = tr.ReadLine();

      while (line != null)
      {
  
         string[] stri = line.Split(' ');

                for (int i = 0; i < stri.Length; i++)
                {
                    if (stri[i].Equals(searchString))
                    {
                        word++;
                    }
                }

                line = tr.ReadLine();
            }

            Console.WriteLine(word.ToString());
}


0 comments: