Search code examples
c#sqlsearcholedbwindows-search

Windows Search query c#


I am trying to search for files containing a phrase or their name contains a phrase.

I achieved to get a query which sometimes has results but I do not get it when and why the results are returned.

This is the query I am using:

SELECT TOP 5 System.ItemPathDisplay 
FROM SystemIndex 
WHERE scope ='file:' 
    AND (FREETEXT('MYPHRASE') 
    OR Contains(System.FileName,'MYPHRASE'))
    AND (Contains(System.ItemType,'.txt') 
    OR Contains(System.ItemType,'.docx') 
    OR Contains(System.ItemType,'.pptx') 
    OR Contains(System.ItemType,'.xlsx') 
    OR Contains(System.ItemType,'.pdf'))

I just want to get all files containing the MYPHRASE name or having it in the content.

This is my oleconnectionstring:

  string connectionString = "Provider=Search.CollatorDSO;Extended Properties=\"Application=Windows\"";
        OleDbConnection connection = new OleDbConnection(connectionString);

can anyone tell me whats wrong with my query?


Solution

  • you could do a recursive search in your c# code like

        void DirSearch(string MYPHRASE) 
    {
        try 
        {
           foreach (string d in Directory.GetDirectories(MYPHRASE)) 
           {
            foreach (string f in Directory.GetFiles(d, txtFile.Text)) 
            {
               lstFilesFound.Items.Add(f);
            }
            DirSearch(d);
           }
        }
        catch (System.Exception excpt) 
        {
            Console.WriteLine(excpt.Message);
        }
    }
    

    which comes from this microsoft article which goes into good detail about how to do it with a full code example. Microsoft also offers a search SDK which could also be helpful depending on your exact situation and may be worth checking out.

    EDIT: Here is a nice blog about doing it in the sql style like you are, and you seem to be on point. he does mention how you may have to get files into the index for them to show up, so may be worth checking into.