Click here to Skip to main content
14,739,471 members
Please Sign up or sign in to vote.
1.50/5 (2 votes)
See more:
With the help of console application in c sharp can we search our data in a text file.

plesse help !
Updated 23-Nov-11 19:17pm

string path = @"c:\somedir";
string searchtext = "something";
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] files = di.GetFiles("*.txt");
foreach (FileInfo file in files)
    using (StreamReader sr = new StreamReader(file.FullName))
        string content = sr.ReadToEnd().ToLower();
            Console.WriteLine("{0} contains \"{1}\"",file.Name,searchtext);
            Console.WriteLine("{0} does not contain \"{1}\"", file.Name, searchtext);
You can search in textfiles using RegularExpressions.Regex.IsMatch
First get the file in StreamReader and read it's content

System.IO.StreamReader reader = new System.IO.StreamReader(file);
String text = reader.ReadToEnd();

use Regular expression to search the text

if (System.Text.RegularExpressions.Regex.IsMatch(text, searchText))
    Console.WriteLine("word found");

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900