Naveen's Weblog

Bridge to future

Search word or phrase within a file using LINQ

Posted by codingsense on September 16, 2008


Hi found a nice way to search a word or phrase within a file, so thought of sharing with you all.

string DirPath = Application.StartupPath + "\Search\";
string SearchText = "Temp";
string[] Files = (from file in new DirectoryInfo(DirPath).GetFiles()
                     where new StreamReader(file.FullName).ReadToEnd().Contains(SearchText)
                     select file.Name).ToArray<string>();


Download Sample – 21 kb

If you know a better way, please post a comment.

Happy Learning 🙂

Advertisements

3 Responses to “Search word or phrase within a file using LINQ”

  1. Manas said

    Thanks naveen.It saved my lot of work………

  2. vj said

    Nice hint. Here is a way to make the code a little more compact(4th line):

    where new File.ReadAllText.Contains(SearchText)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: