+92 332 4229 857 99ProjectIdeas@Gmail.com

Count Words In File (C#.net)

The following code shows how to count words in file, a function CountWords() takes parameter of textFile path from where the words are to be searched. Reading a file line by line and splitting at every space and count the length of new string array.

using System.IO;

public void CountWords(string filePath)

      TextReader tr = File.OpenText(filePath);

      int countWords = 0;

      string line = tr.ReadLine();

      while (line != null)

           string[] str = line.Split(' ');

           countWords += str.Length;

           line = tr.ReadLine();