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: May 7, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT This eSeminar will explore three popular games engines and how they empower developers to create exciting, graphically rich, and high-performance games for Android® on Intel® Architecture. Join us for a deep dive as experts describe the features, tools, and common challenges using Marmalade, App Game Kit, and Havok game engines, as well as a discussion of the pros and cons of each engine and how they fit into your development …

  • The exponential growth of data, along with virtualization, is bringing a disruptive level of complexity to your IT infrastructure. Having multiple point solutions for data protection is not the answer, as it adds to the chaos and impedes on your ability to deliver consistent SLAs. Read this white paper to learn how a more holistic view of the infrastructure can help you to unify the data protection schemas by properly evaluating your business needs in order to gain a thorough understanding of the applications …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds