Find File Content Using the .NET IO Class

Environment: C#, Win9x/2000/XP

This is a very simple application that uses the .NET I/O class to search the files' content in a directory. I first used a DirectoryInfo class to get the directory information. Then, I saved the file list in a FileInfo array. You loop through the array and open each file for reading. Convert the buffer to string type, find the text, and raise an event when it's found.

The searching process can be time consuming. We can use the .NET delegate function to search asynchronously, as show below.

//declare a delegate function
private delegate void FindAsyn();

[STAThread]
static void Main(string[] args)
{

  FileFind ff = new FileFind();

  //subscribe the found file event
  ff.OnFileFound += new FoundDelegate(OnFoundFile);

  //The directory to be searched
  ff.PathName = @"C:\MyFileDir";
  //The text to be searched
  ff.FindText ="findtext";

  //delegate to...
  FindAsyn f = new FindAsyn(ff.StartSearch);
  //invoke the searching function asynchronously
  f.BeginInvoke(null,null);
  Console.Read();             // pause the screen;
  FileFind.bStopIt = true;    // stop it if the process takes
                              // too long.
  Console.Read();
  //unsubscribe the event
  ff.OnFileFound -= new FoundDelegate(OnFoundFile);

}

private static void OnFoundFile(string filename)
{
  Console.WriteLine(filename);
}

Downloads

Download demo project - 7 Kb
Download source - 3 Kb


Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • CentreCorp is a fully integrated and diversified property management and real estate service company, specializing in the "shopping center" segment, and is one of the premier retail service providers in North America. Company executives travel a great deal, carrying a number of traveling laptops with critical current business data, and no easy way to back up to the network outside the office. Read this case study to learn how CentreCorp implemented a suite of business continuity services that included …

Most Popular Programming Stories

More for Developers

RSS Feeds