Click here to Skip to main content
15,886,065 members
Articles / Programming Languages / C#

Source Code Super Search

Rate me:
Please Sign up or sign in to vote.
4.71/5 (22 votes)
10 Mar 2009CPOL8 min read 52.3K   1.5K   66  
A simple solution for searching source code directories
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace BSCodeGrep
{
    public class IOWorker
    {
        private int m_SearchedCount;
        private List<string> m_idx;
        private List<SearchResult> m_results;
        private SearchSettings m_uso;

        /// <summary>
        /// The amount of items searched through
        /// </summary>
        public int SearchedCount
        {
            get
            {
                return m_SearchedCount;
            }
        }

        /// <summary>
        /// Returns the results of the search
        /// </summary>
        public List<SearchResult> GetSearchResults
        {
            get
            {
                return m_results;
            }
        }

        /// <summary>
        /// User Defined Search Options
        /// </summary>
        public SearchSettings UserSearchOptions
        {
            get
            {
                return m_uso;
            }
            set
            {
                m_uso = value;
            }
        }

        /// <summary>
        /// Constructor
        /// </summary>
        public IOWorker(SearchSettings uso)
        {
            m_idx = new List<string>();
            m_results = new List<SearchResult>();
            m_uso = uso;
        }

        /// <summary>
        /// Creates the index of the user defined root path
        /// </summary>
        public void CreateIdx()
        {
            foreach (string f in m_uso.filters)
            {
                try
                {
                    m_idx.AddRange(Directory.GetFiles(
                        m_uso.path, "*" + f, 
                        SearchOption.AllDirectories));
                }
                catch (UnauthorizedAccessException e)
                {
                    System.Diagnostics.Debug.WriteLine(e);
                }                
            }
            //m_idx.Reverse();
            m_SearchedCount = m_idx.Count;
            SearchResults(m_uso.pattern);
        }

        private void SearchResults(string searchPattern)
        {
            for (int i = 0; i < m_idx.Count; i++)
            {
                SearchResult sri = new SearchResult();

                if (!m_uso.NamesOnly)
                {
                    try
                    {
                        using (StreamReader sr = new StreamReader(m_idx[i]))
                        {
                            String line;
                            int p = 0;

                            while ((line = sr.ReadLine()) != null)
                            {
                                p++;
                                if (Regex.IsMatch(line, searchPattern))
                                {
                                    sri.FilePath = m_idx[i];
                                    sri.Lines.Add(p.ToString() + ": " + line);
                                }
                            }
                            if (sri.Lines.Count > 0)
                                m_results.Add(sri);
                        }
                    }
                    catch(SystemException e)
                    {
                        sri.FilePath = m_idx[i];
                        sri.Error = e;
                    }
                }
                else
                {
                    if (Regex.IsMatch(m_idx[i], searchPattern))
                    {
                        sri.FilePath = m_idx[i];
                        m_results.Add(sri);
                    }
                }
            }
        }

        #region depreciated cli methods
        //public void CreateIdx()
        //{
        //    StreamWriter sw = File.CreateText(m_cmd);
        //    StreamWriter swr = File.CreateText(m_idx);

        //    foreach (string f in m_uso.filters)
        //    {
        //        sw.WriteLine("{0} \"{1}\" >> {2}",
        //                     "dir /B /S",
        //                     m_uso.path + "\\*" + f,
        //                     m_idx);
        //    }
        //    sw.Flush();
        //    sw.Close();
        //    swr.Flush();
        //    swr.Close();

        //    CommandLine cli = new CommandLine(ExecutionType.SHELL_EXECUTE_HIDDEN);
        //    cli.ExecuteCommand(m_cmd, "", null);
        //    PopulateIdx();
        //    SearchResults(m_uso.pattern);
        //}

        //private void PopulateIdx()
        //{
        //    using (StreamReader sr = new StreamReader(m_idx))
        //    {
        //        String line;
        //        while ((line = sr.ReadLine()) != null)
        //        {
        //            p_idx.Add(line);
        //        }
        //    }
        //    m_SearchedCount = p_idx.Count;
        //}

        #endregion

        /// <summary>
        /// User Defined Search Parameters
        /// </summary>
        public struct SearchSettings
        {
            /// <summary>
            /// Starting search path
            /// </summary>
            public string path;

            /// <summary>
            /// The file extensions to search
            /// </summary>
            public string[] filters;

            /// <summary>
            /// The pattern to match in the file name or in the file
            /// </summary>
            public string pattern;

            /// <summary>
            /// Search file names only {bool)
            /// </summary>
            public bool NamesOnly;
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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


Written By
Software Developer
United States United States
I'm a professional .NET software developer and proud military veteran. I've been in the software business for 20+ years now and if there's one lesson I have learned over the years, its that in this industry you have to be prepared to be humbled from time to time and never stop learning!

Comments and Discussions