Click here to Skip to main content
15,886,519 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 !
Posted
Updated 23-Nov-11 18:17pm
v2

C#
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();
        if(content.Contains(searchtext.ToLower()))
            Console.WriteLine("{0} contains \"{1}\"",file.Name,searchtext);
        else
            Console.WriteLine("{0} does not contain \"{1}\"", file.Name, searchtext);
    }
}
 
Share this answer
 
You can search in textfiles using RegularExpressions.Regex.IsMatch
First get the file in StreamReader and read it's content

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


use Regular expression to search the text

C#
if (System.Text.RegularExpressions.Regex.IsMatch(text, searchText))
{
    Console.WriteLine("word found");
}
 
Share this answer
 

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