środa, 1 kwietnia 2009

Microsoft Windows Search API

Aby móc korzystać w aplikacjach z wbudowanego w Windows search'a należy do projetu dodać referencje Microsoft.Search.Interop. Można ją pobrać wraz z przykładowymi aplikacjami tutaj.
Przeszukiwanie zródeł lokalnych polega na przeszukiwaniu przy pomocy OleDbConnection katalogu SystemIndex. Poniżej zamieszam przykład zastosowania



CSearchManager manager = new CSearchManager();
// the SystemIndex catalog is the default catalog that windows uses
CSearchCatalogManager catalogManager = manager.GetCatalog("SystemIndex");

// get the ISearchQueryHelper which will help us to build SQL necessary to query the indexer
CSearchQueryHelper queryHelper = catalogManager.GetQueryHelper();
//we get which column we can obtain (in this example file path and file name)
queryHelper.QuerySelectColumns = "System.ItemPathDisplay,System.FileName";

string dir = @"C:\" //path in which we want search
// then we add a scope in format of

queryHelper.QueryWhereRestrictions = "AND scope='file:" + dir + "' AND Contains(System.ItemType,'\".pdf\"') ";//we can search only specyfied type of file in this example pdf


// Generate SQL from our parameters
string sqlQuery = queryHelper.GenerateSQLFromUserQuery(searchPhraze);


// --- Perform the query ---
// create an OleDbConnection object which connects to the indexer provider with the windows application
System.Data.OleDb.OleDbConnection conn = new OleDbConnection(queryHelper.ConnectionString);

// open it
conn.Open();

// now create an OleDB command object with the query we built above and the connection we just opened.
OleDbCommand command = new OleDbCommand(sqlQuery, conn);

// execute the command, which returns the results as an OleDbDataReader.
OleDbDataReader WDSResults = command.ExecuteReader();

while (WDSResults.Read())
{
string filePath = WDSResults.GetString(0);
string filename = WDSResults.GetString(1);


});
}

WDSResults.Close();
conn.Close();