Searching Indexing Service (ASP.NET C#)

Windows has an Indexing Service that can be used to index files on the server it is hosted on. Here is a simple way to query any catalogues (in this example, one called Data) you create and display the results in a repeater.

First of all, create a new page (in Visual Studio or Web Developer 2005), e.g. search.aspx. Create the search box and repeater within a form runat="server":

<form id="form1" runat="server">
<div>
 <asp:TextBox runat="server" ID="Search" />
 <asp:Button runat="server" Text="Search" OnClick="SearchDocuments" />
 <asp:Repeater ID="ResultsRepeater" runat="server">
  <HeaderTemplate>
   <table>
    <thead>
     <tr>
      <th>
       Filename
      </th>
      <th>
       Size
      </th>
      <th>
       Title
      </th>
      <th>
       Path
      </th>
      <th>
       Last Modified
      </th>
      <th>
       Rank
      </th>
     </tr>
    </thead>
    <tbody>
  </HeaderTemplate>
  <ItemTemplate>
   <tr>
    <td>
     <%# Eval("Filename") %>
    </td>
    <td>
     <%# Eval("size") %>
    </td>
    <td>
     <%# Eval("DocTitle") %>
    </td>
    <td>
     <%# Eval("path") %>
    </td>
    <td>
     <%# Eval("write") %>
    </td>
    <td>
     <%# Eval("rank") %>
    </td>
   </tr>
  </ItemTemplate>
  <FooterTemplate>
   </tbody> </table></FooterTemplate>
 </asp:Repeater>
</div>
</form>

Then in your code behind (search.aspx.cs) add:

protected void SearchDocuments(object sender, EventArgs e)
{
 String fileTypes = "\".doc\" OR \".rtf\"";
 String catalog = "Data";
 String q = Search.Text;
 q = q.Replace("'", "''");

 String query = "SELECT DocTitle,Filename,size,path,rank,write,vpath,url from SCOPE() WHERE FREETEXT('"+q+"') AND CONTAINS(Filename, '"+fileTypes+"') ORDER BY rank DESC, write DESC";

 OleDbConnection cn = new OleDbConnection("Provider=MSIDXS.1;Integrated Security .='';Data Source='Data'");

 OleDbDataAdapter cmd = new OleDbDataAdapter(query, cn);

 DataSet data = new DataSet();
 cmd.Fill(data);

 DataView results = new DataView(data.Tables[0]);

 ResultsRepeater.DataSource = results;
 ResultsRepeater.DataBind();

}

The results are sorted by rank (highest first), then date last modified (newest first). Only search Word documents (or more precisely, filenames containing .doc or .rtf) - but you can always add more types and refine the search further.

Comments

Anonymous said…
Hi, can u help me to solve a problem?
i have develop a system which will save a document file in sql server after user upload
now my problem is i wan to search document content from database
hw can i do tat using sql query?
thx
Sam said…
That is something I have been try to figure out as well... I have looked at Lucene.Net, but not got very far with it

Popular posts from this blog

Link: HTML Agility Pack (.NET)

Basic Excel Spreadsheet Generation (ASP/ASP.NET)

ASP.NET: Binding alphabet to dropdown list