+92 332 4229 857 99ProjectIdeas@Gmail.com

Search A Word In File Through LINQ (C#.net)

Search A Word In File Through LINQ (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 through LINQ. Reading a whole file in one string through ReadToEnd() function and splitting at every space. Now put query and select all those strings which are equal to searchString. And with the help of Count() function count the word how many times it occur in that file.


using System.IO;
using System.Linq;

public void SearchWord(string filePath, string searchString)

    TextReader tr = File.OpenText(filePath);

    string[] str = tr.ReadToEnd().Split(' ');

    var query =
        from string s in str
        where s.Equals(searchString)
        select s;