Sunday, April 1, 2012

Fast file searching in C#

This code shows how can you search for a file in C# using windows index and OleDB. The code below is tested in windows Vista where file indexing is enable by default. The following function, when called, outpust the fullpath of the file in request. It uses the operating system's file index therefore is very fast!


using System;
using System.Data.OleDb;

namespace MyBrowser
{
    class Browser
    {
        public void findFile(string fileName)
        {
            
            try
            {
                string url = "provider=Search.CollatorDSO.1;" +
                    "EXTENDED PROPERTIES=\"Application=Windows\"";
                OleDbConnection connection = new OleDbConnection(url);
                string queryString = "Select System.ItemPathDisplay from "+
                    "SystemIndex where System.FileName ='" + fileName + "' ";
                Console.WriteLine(queryString);
                OleDbCommand command = new OleDbCommand(queryString, connection);
                connection.Open();
                OleDbDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine(reader[0].ToString());
                }
                reader.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            
        }
    }
}