Click here to Skip to main content
14,665,013 members
Rate this:
Please Sign up or sign in to vote.
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

Rate this:
Please Sign up or sign in to vote.

Solution 1

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);
    }
}
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

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, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100