Click here to Skip to main content
12,451,093 members (45,007 online)
Click here to Skip to main content
Add your own
alternative version

Stats

165.6K views
4.6K downloads
150 bookmarked
Posted

WinSearchFile: how to search files on your PC

, 24 Feb 2006 CPOL
Rate this:
Please Sign up or sign in to vote.
Sometimes the search engine integrated with Explorer doesn't work fine, especially when I try to find text contained into files, so I decided to build my own search program.

Sample Image - WinSearchFile.jpg

Introduction

WinSearchFile is a program that I developed and I usually use it to search files on my PC.

Sometimes the search engine integrated with Explorer doesn't work fine, especially when I try to find text contained into files, so I decided to build my own search program.

There are a lot of search programs available to install on your PC but this one, without indexing your data, is simple and fast enough to help you in your search.

Inside the application

WinSearchFile layout is simple and quite similar to the Explorer integrated search. It is possible to write a pattern search (wildcards admitted) and/or a text to search into file contents (you can also decide for a case sensitive search).

In the "look in" area, you have all the disks of your computer (network connection included). To obtain this list, I use the DiskCollection class developed by dmihailescu in his Get Logical Drives Information article.

/// <SUMMARY>
/// Add items for all floppy, 
/// CD and hard drives.
/// </SUMMARY>
private void LoadDisksComboBox()
{
    disksListBox.Items.Clear();

    // Try to use DiskCollection
    // retrieving drive information
    DiskCollection diskColl = new DiskCollection();
    if ( diskColl.Load() )
    {
        foreach(DiskCollection.LogicalDriveInfo diskinfo in diskColl)
        {
            disksListBox.Items.Add(diskinfo.Name.ToString() + 
                                ": "+ diskinfo.Description );

        }
    }
    else
    {
        // otherwise build a drive list checking 
        // if a root directory exists
        for (char Ch = 'A'; Ch <= 'Z'; Ch++)
        {
            string Dir = Ch + @":\";

            if (Directory.Exists(Dir))
            {
                disksListBox.Items.Add( Ch+ @":" );
            }
        }
    }
}

Application shows alerts when you check a not-ready disk.

Disk Not ready Sample Image - notready.jpg

In the WinSearchFile application, I use threads to make the same search simultaneously on different targets; I use a thread for each target drive.

/// <SUMMARY>
/// Start search
/// </SUMMARY>
/// <PARAM name="sender"></PARAM>
/// <PARAM name="e"></PARAM>
private void btnSearch_Click(object sender, System.EventArgs e)
{

    // empty thread list
    for (int i = thrdList.ItemCount()-1; i>=0; i--)
    {
        thrdList.RemoveItem(i);
    }

    // clear the file founded list
    listFileFounded.Items.Clear();
    ContainingFolder = "";

    // get the search pattern
    // or use a default
    SearchPattern = txtSearchPattern.Text.Trim();
    if (SearchPattern.Length == 0)
    {
        SearchPattern = "*.*";
    }

    // get the text to search for
    SearchForText = txtSearchText.Text.Trim();

    // clear the Dirs arraylist
    Dirs.Clear();

    // check if each selected drive exists
    foreach (int Index in disksListBox.CheckedIndices)
    {
        // chek if drive is ready
        String Dir = disksListBox.Items[Index].ToString().Substring(0,2);
        Dir += @"\";
        if (CheckExists(Dir))
        {
            Dirs.Add(Dir);
        }
    }

    // I use 1 thread for each dir to scan
    foreach (String Dir in Dirs)
    {
        Thread oT;
        string thrdName = "Thread" + ((int)(thrdList.ItemCount()+1)).ToString();
        FileSearch fs = new FileSearch(Dir, SearchPattern, 
                        SearchForText, CaseSensitive, this, thrdName);
        oT = new Thread(new ThreadStart(fs.SearchDir));

        oT.Name = thrdName;

        SearchThread st = new SearchThread();
        st.searchdir = Dir;
        st.name = oT.Name;
        st.thrd = oT;
        st.state = SearchThreadState.ready;
        thrdList.AddItem(st);
        oT.Start();
    }
}

Data about searching threads is stored in a list, and during the search process, you can see how many threads are running/ready/cancelled.

Searching Sample Image - main2.jpg

Threads use the FileSearch class to do their work. To update controls or data structures on main threads, use delegate functions. I defined a delegate function for the AddListBoxItem method:

/// <SUMMARY>
/// Delegate for AddListBoxItem
/// </SUMMARY>
public delegate void AddListBoxItemDelegate(String Text);

/// <SUMMARY>
/// Add a new item to the file founded list
/// </SUMMARY>
/// <PARAM name="Text"></PARAM>
public void AddListBoxItem(String Text)
{
    // I use Monitor to synchronize access 
    // to the file founded list
    Monitor.Enter(listFileFounded);

    listFileFounded.Items.Add(Text);

    Monitor.Exit(listFileFounded);
}

and one to update the thread state:

/// <SUMMARY>
/// Delegate for UpdateThreadStatus function
/// </SUMMARY>
public delegate void UpdateThreadStatusDelegate(String thrdName, 
                                         SearchThreadState sts);

/// <SUMMARY>
/// Store the new state of a thread
/// </SUMMARY>
/// <PARAM name="thrdName"></PARAM>
/// <PARAM name="sts"></PARAM>
public void UpdateThreadStatus(String thrdName, SearchThreadState sts)
{
    SearchThread st = thrdList.Item(thrdName);
    st.state = sts;
}

On clicking the "Stop search" button, all the running threads are cancelled using the Abort method.

/// <SUMMARY>
/// Stop searching
/// </SUMMARY>
/// <PARAM name="sender"></PARAM>
/// <PARAM name="e"></PARAM>
private void btnStop_Click(object sender, System.EventArgs e)
{
    // some threads are running
    if (InProgress)
    {
        // Abort each searching thread in running status
        // and change its status to cancelled
        for (int i= 0; i < thrdList.ItemCount(); i++)
        {
            if (((SearchThread)thrdList.Item(i)).state == 
                               SearchThreadState.running)
            {
                ((SearchThread)thrdList.Item(i)).state = 
                            SearchThreadState.cancelled;
                Thread tt;
                try
                {
                    tt = ((SearchThread)thrdList.Item(i)).thrd;
                    tt.Abort();
                }
                catch
                {
                }
            }
        }

    }
}

On double clicking on a result listbox item, WinSearchFile will open the corresponding containing folder.

Open Containing Folder - dblclick.jpg

To quick launch WinSearchFile, you can create a shortcut to it on your desktop and assign to this one a shortcut key.

Shortcut Sample Image - shortcut.jpg

Conclusion

I hope you enjoy this article.

New WinSearchFile version

The new WinSearchFile 2.0, built using Visual Studio 2005 and C# 2.0, contains the following new features:

  • Single Instance Application using code written by Eric Bergman-Terrell.
  • Search inside PDF files.
  • Regular expression searching.
  • Searching using IFilter.
  • Max directory visit depth.
  • File Creation Time or Last ACcess Time or Last Write Time searching
  • directory list to search into.
  • Save results button.

Here is a new screenshot:

Sample Image - winsearchfile20.jpg

About IFilter

User can decide to use installed IFilter to extract plaintext from files. To implement this interface I used 2 class developed by Dan Letecky.

The following code shows where I try to use IFilter to get plaintext:

public static bool FileContainsText(String FileName, 
          String SearchForText, bool CaseSensitive, 
          bool UseRegularExpression, bool UseIFilter)
{
    bool Result = (SearchForText.Length == 0);

    if (!Result)
    {
      // try to use IFilter if you have checked
      // UseIFilter checkbox
     if (Parser.IsParseable(FileName) && UseIFilter)
     {
         string content = Parser.Parse(FileName);
         // if content length > 0
         // means that IFilter works and returns the file content
         // otherwise IFilter hadn't read the file content
         // i.e. IFilter seems no to be able to extract
         // text contained in dll or exe file
         if (content.Length > 0)
         {
             Result = containsPattern(SearchForText, 
                      CaseSensitive, UseRegularExpression, content);
             return Result;
         }
      }
      // scan files to get plaintext
      // with my routines
      if (FileName.ToLower().EndsWith(".pdf"))
      {
         // search text in a pdf file
         Result = SearchInPdf(FileName, SearchForText, 
                  CaseSensitive, UseRegularExpression);
      }
      else
      {
         bool Error;
         String TextContent = GetFileContent(FileName, out Error);

         if (!Error)
         {
            Result = containsPattern(SearchForText, 
                     CaseSensitive, UseRegularExpression, TextContent);
         }
      }
    }

    return Result;
}

The following screenshot shows the about box where it's possible to get the list of installed IFilter. To get this list I used a class developed by vbAccelerator.com.

Sample Image - winsearchfile_aboutbox.jpg

License

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

Share

About the Author

Massimo Beatini
Web Developer
Italy Italy
No Biography provided

You may also be interested in...

Pro
Pro

Comments and Discussions

 
GeneralUsing Logical And / OR Operator Pin
SenthilMedaz7-Sep-09 20:35
memberSenthilMedaz7-Sep-09 20:35 
GeneralWhy dont you extract File creation/Access time from IFilter Pin
aaquib15-Apr-08 21:40
memberaaquib15-Apr-08 21:40 
GeneralNice job Pin
djonio24-Oct-07 1:39
memberdjonio24-Oct-07 1:39 
GeneralGood Idea but shame that the GUI is not separated from the rest Pin
Nice Life5-Jun-07 1:24
memberNice Life5-Jun-07 1:24 
GeneralRe: Good Idea but shame that the GUI is not separated from the rest Pin
Inge_Octavio17-Jun-07 5:29
memberInge_Octavio17-Jun-07 5:29 
GeneralRe: Good Idea but shame that the GUI is not separated from the rest Pin
Nice Life17-Jun-07 19:55
memberNice Life17-Jun-07 19:55 
Generaluser Pin
zmrcic23-Feb-07 1:01
memberzmrcic23-Feb-07 1:01 
AnswerRe: user Pin
Massimo Beatini23-Feb-07 2:31
memberMassimo Beatini23-Feb-07 2:31 
GeneralRe: user Pin
zmrcic23-Feb-07 2:37
memberzmrcic23-Feb-07 2:37 
AnswerRe: user Pin
Massimo Beatini23-Feb-07 3:10
memberMassimo Beatini23-Feb-07 3:10 
GeneralRe: user Pin
zmrcic23-Feb-07 3:17
memberzmrcic23-Feb-07 3:17 
GeneralRe: user Pin
Red Flying Pig10-Jul-08 7:19
memberRed Flying Pig10-Jul-08 7:19 
GeneralError: Searching on 'Last access time' instead of 'Creation Time' Pin
Lars Hellqvist6-Feb-07 15:34
memberLars Hellqvist6-Feb-07 15:34 
AnswerRe: Error: Searching on 'Last access time' instead of 'Creation Time' Pin
Massimo Beatini7-Feb-07 3:25
memberMassimo Beatini7-Feb-07 3:25 
Questionthe program doen't find any file Pin
micheal_safian28-Sep-06 10:04
membermicheal_safian28-Sep-06 10:04 
GeneralGreat Job Pin
Bassam Abdul-Baki15-May-06 4:45
memberBassam Abdul-Baki15-May-06 4:45 
Generalvery cool, but why not use flexible renamer Pin
Darchangel3-Mar-06 10:32
memberDarchangel3-Mar-06 10:32 
GeneralProblem with windows explorer Pin
dreidemy28-Feb-06 21:14
memberdreidemy28-Feb-06 21:14 
AnswerRe: Problem with windows explorer Pin
Massimo Beatini28-Feb-06 21:34
memberMassimo Beatini28-Feb-06 21:34 
GeneralRe: Problem with windows explorer Pin
Jason Barry26-Aug-08 9:47
memberJason Barry26-Aug-08 9:47 
GeneralSome improvement Pin
Oleg Shilo22-Feb-06 11:34
memberOleg Shilo22-Feb-06 11:34 
AnswerRe: Some improvement Pin
Massimo Beatini22-Feb-06 22:32
memberMassimo Beatini22-Feb-06 22:32 
Generalre: Explorer search doesn't always work Pin
grundt22-Feb-06 10:09
membergrundt22-Feb-06 10:09 
GeneralRe: re: Explorer search doesn't always work Pin
The_Mega_ZZTer22-Feb-06 14:38
memberThe_Mega_ZZTer22-Feb-06 14:38 
GeneralRe: re: Explorer search doesn't always work Pin
mahendren27-Feb-06 18:41
membermahendren27-Feb-06 18:41 
GeneralConsider IFilter integration Pin
vektuz22-Feb-06 9:05
membervektuz22-Feb-06 9:05 
AnswerRe: Consider IFilter integration Pin
Massimo Beatini25-Feb-06 6:31
memberMassimo Beatini25-Feb-06 6:31 
GeneralSome nice features to include ... Pin
malharone8-Feb-06 4:57
membermalharone8-Feb-06 4:57 
AnswerRe: Some nice features to include ... Pin
Massimo Beatini22-Feb-06 21:00
memberMassimo Beatini22-Feb-06 21:00 
Generalwhy only c#... why not java Pin
yatresh21-Jan-06 22:28
memberyatresh21-Jan-06 22:28 
GeneralRe: why only c#... why not java Pin
Colin Angus Mackay21-Jan-06 22:58
memberColin Angus Mackay21-Jan-06 22:58 
Generalhow i can use your codes Pin
yatresh22-Jan-06 9:48
memberyatresh22-Jan-06 9:48 
AnswerRe: how i can use your codes Pin
Massimo Beatini5-Feb-06 8:43
memberMassimo Beatini5-Feb-06 8:43 
GeneralAiuto Massimo Pin
sat0420-Dec-05 20:01
membersat0420-Dec-05 20:01 
AnswerRe: Aiuto Massimo Pin
Massimo Beatini8-Jan-06 22:45
memberMassimo Beatini8-Jan-06 22:45 
Generalbool for Recursive Folder search Pin
pxp12-Aug-05 5:41
memberpxp12-Aug-05 5:41 
GeneralSimple modifications to search inside Pdf files (final) Pin
Massimo Beatini22-Jun-05 23:19
sussMassimo Beatini22-Jun-05 23:19 
GeneralSimple modifications to search inside Pdf files Pin
Massimo Beatini22-Jun-05 5:20
sussMassimo Beatini22-Jun-05 5:20 
GeneralRe: Simple modifications to search inside Pdf files Pin
age_getty22-Jun-05 22:34
memberage_getty22-Jun-05 22:34 
GeneralRe: Simple modifications to search inside Pdf files Pin
Massimo Beatini22-Jun-05 22:59
sussMassimo Beatini22-Jun-05 22:59 
QuestionHow To Search Text In PDF Files? Pin
XiaoYu21-Jun-05 15:48
memberXiaoYu21-Jun-05 15:48 
AnswerRe: How To Search Text In PDF Files? Pin
Massimo Beatini22-Jun-05 5:24
sussMassimo Beatini22-Jun-05 5:24 
GeneralIt doesnt find anything Pin
Foxandxss13-Jun-05 11:24
memberFoxandxss13-Jun-05 11:24 
GeneralRe: It doesnt find anything Pin
Massimo Beatini13-Jun-05 21:40
sussMassimo Beatini13-Jun-05 21:40 
GeneralRe: It doesnt find anything Pin
Foxandxss13-Jun-05 22:24
memberFoxandxss13-Jun-05 22:24 
GeneralRe: It doesnt find anything Pin
Massimo Beatini13-Jun-05 22:31
sussMassimo Beatini13-Jun-05 22:31 
GeneralRe: It doesnt find anything Pin
Foxandxss13-Jun-05 22:38
memberFoxandxss13-Jun-05 22:38 
GeneralRe: It doesnt find anything Pin
Massimo Beatini13-Jun-05 23:28
sussMassimo Beatini13-Jun-05 23:28 
GeneralRe: It doesnt find anything Pin
Foxandxss13-Jun-05 23:53
memberFoxandxss13-Jun-05 23:53 
GeneralRe: It doesnt find anything Pin
Massimo Beatini13-Jun-05 23:58
sussMassimo Beatini13-Jun-05 23:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160826.1 | Last Updated 24 Feb 2006
Article Copyright 2005 by Massimo Beatini
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid