Aug 30, 2010

Sharepoint search in document library/list programmatically (using C#)

In sharepoint, it is generally required to limit search to a particular list or document library and display metadata properties. The example below shows an example FullTextSql query using the PATH managed property to limit your search to a particular list, and then the results are used to create the list item. You can bind results to gridview and can show metadata properties.You need to pass document library url and search text in the following method:


public List<SPListItem> GetListItemsFromFTSQuery(string docLibUrl, string searchText)
{

List<SPListItem> items = new List<SPListItem>();
DataTable retResults = new DataTable();

using (SPSite site = new SPSite(docLibUrl))
{
SPWeb CRsite = site.OpenWeb();
SPList ContRep = CRsite.GetListFromUrl(docLibUrl);

FullTextSqlQuery fts = new FullTextSqlQuery(site);           
fts.QueryText = "SELECT Title,ContentType,Path FROM portal..scope() WHERE freetext('" + searchText + "') AND (CONTAINS(Path,'\"" + ContRep.RootFolder.ServerRelativeUrl + "\"'))";
fts.ResultTypes = ResultType.RelevantResults;
fts.RowLimit = 300;

ResultTableCollection rtc = fts.Execute();
if (rtc.Count > 0)
{

using (ResultTable relevantResults = rtc[ResultType.RelevantResults])
retResults.Load(relevantResults, LoadOption.OverwriteChanges);

foreach (DataRow row in retResults.Rows)
{
if (!row["Path"].ToString().EndsWith(".aspx"))//if (row["ContentType"].ToString() == "Item")
{
using (SPSite lookupSite = new SPSite(row["Path"].ToString()))
{
using (SPWeb web = lookupSite.OpenWeb())
{
SPFile file = web.GetFile(row["Path"].ToString());
items.Add(file.Item);

}
}
}
}

}
return items;
}
}

Enjoy it.