how can i search in text files by c#
-
hi every body i want know how can i search in text files (*.doc,*.txt) by c# I want give the program specefic folder and it will search in all files in it how can i do this ?? thanks in advance
-
hi every body i want know how can i search in text files (*.doc,*.txt) by c# I want give the program specefic folder and it will search in all files in it how can i do this ?? thanks in advance
i dont know about *.doc files cause the format is different from *.txt Youll use the DirectoryInfo class to get a list of all the text files within it. then you can foreach that list and inside the loop create a fileStream that you point to the path of the current item in the loop. You then need to create a StreamReader and point it to your fileStream. you can then declare a string variable and call StreamReader.ReadToEnd(). after that you can use String.Contains("Text your looking for") to see if you text is in fact in your file! Heres an example in C#
// Create a DirectoryInfo class and point it to the
// directory you want to search in
DirectoryInfo dirInf = new DirectoryInfo(@"C:\");// Create a FileInfo array and get the file information
// of all the TXT files in the directory
FileInfo[] files = dirInf.GetFiles("*.txt");// Loop though all the files found
foreach (FileInfo currentFile in files)
{
// Create a files stream
FileStream fs = new FileStream(currentFile.FullName, FileMode.Open);//create a stream reader StreamReader reader = new StreamReader(fs); //read the text in the file string fileContent = reader.ReadToEnd(); if (fileContent.Contains("the text your searching for")) { MessageBox.Show("The File " + currentFile.FullName + " Contains the text your searching for"); } // flush and close the IO objects fs.Flush(); reader.Close(); fs.Close();
}
remember to add
using System.IO;
Harvey Saayman - South Africa Junior Developer .Net, C#, SQL
you.suck = (you.Passion != Programming & you.Occupation == jobTitles.Programmer)
1000100 1101111 1100101 1110011 100000 1110100 1101000 1101001 1110011 100000 1101101 1100101 1100001 1101110 100000 1101001 1101101 100000 1100001 100000 1100111 1100101 1100101 1101011 111111