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: July 30, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT You may already know about some of the benefits of Bluemix, IBM's open platform for developing and deploying mobile and web applications. Check out this upcoming eSeminar that focuses on building an Android application using the MobileData service, with a walk-through of the real process and workflow used to build and link the MobileData service within your application. Join IBM's subject matter experts as they show you the way to build a base …

  • Where the business performance of their mobile app portfolios are concerned, most companies are flying blind. While traditional application portfolios are held to all kinds of ROI measure, the investment plan for mobile apps -- increasingly the more crucial bet -- is made by guesswork and dart-throwing. This interactive e-book investigates how mobile is driving the need for app and portfolio measures unlike any we saw in the days of web. Good mobile analytics must deliver leading indicators of user experience …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds