Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

C# FileSearch

2.00/5 (2 votes)
8 Sep 2013CPOL2 min read 17.6K   657  
Search for file using regualar expression or classic *.*

Introduction

Windows 7 file search is BROKEN! It skips folders, it is hard to use, you have to use the control panel to add file types... It just doesn't work the way most people want it to work.

This simple utility lets you easily search for file by name or contents. You can use the classic *.* format or regular expressions. No fancy date or size filtering, but the student can add that. It doesn't skip folders, it doesn't make you guess how to use it - it just works. This version includes more file information, and the ability to sort each column.

Using the Code

This is a standalone utility. The methods it demonstrates is recursive file searching, using .NET regular expressions, and some basic controls and dialogues.

The only mildly interesting code is the file recursion, below, the rest is pretty standard and simple.

C#
private void AddListItemDetails(FileInfo info)
     {
     ListViewItem item = new ListViewItem(info.FullName);
     item.SubItems.Add(info.Length.ToString());
     item.SubItems.Add(info.CreationTime.ToString());
     item.SubItems.Add(info.LastWriteTime.ToString());
     item.SubItems.Add(info.Extension);

     listViewResults.Items.Add(item);
     } 
// recurse the path and add found files to the listbox, normal mode
private void RecursePath(string fileName, string path, string contains)
{
try
    {
        DirectoryInfo dir = new DirectoryInfo(path);

    foreach (FileInfo info in dir.GetFiles(fileName) )
        {
                if (contains.Length < 1)
                    AddListItemDetails(info);
                else
                    {
                        if (FileContains(info.FullName, contains))
                            AddListItemDetails(info);
                        }
                     
        }

         foreach (DirectoryInfo info in dir.GetDirectories())
             {
                RecursePath(fileName, info.FullName, contains);
                }
    }
catch (Exception ex)
    {
    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}  

This uses DirectoryInfo.GetFiles to list all the files in the current directory and add them to the list box. DirectorInfo gets the file basic information as well as the file name. Then it recursively calls itself on each folder, then it does the same thing again. If it finds more folders, it calls itself to add its files to the listview. It repeats this until it lists the files in a folder with no sub-folders. This will get all the files, in all the folders, and their sub-folders, you start at. This is a very basic use of recursion to traverse a simple tree.

A similar function does the same thing, but uses the C# regex functions to match file names and content. Regex is a very powerful and flexible way to match text and makes this file search much more useful.

A class to sort the columns is implemented based on IComparer. See ListViewColumnSorter is the source code for the details.

A simple context menu is also enabled to allow you to open a file, copy its name to the clipboard, open the file's path in explorer, and export the whole list to a text file. I've added a right-click handler to select lines in the list before invoking the context menu so that the line you right-click on is selected.

C#
// by default a right click doesn't select an item in a listbox, 
// make it do a select so the menu
// context executes on the correct item
private void listBoxResults_MouseDown(object sender, MouseEventArgs e)
    {
    if (e.Button == MouseButtons.Right)
        {
        int index = listBoxResults.IndexFromPoint(e.Location);
        if (index != ListBox.NoMatches)
            {
            listBoxResults.SelectedIndex = index;
            contextMenuStripListBoxResults.Show();
            }
        }
    } 

History

  • Initial version
  • Updated version: column information, sort columns

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)