很早就知道Lucene.Net但一直都没时间认真实践一下.最近项目需要.所以考虑学习一下Lucene.Net引擎.终于做出了第一个Demo感觉挺实用的.还不错.代码贴上.各位博友可参考学习一下.
protected void btnAddIndex_Click(object sender, EventArgs e)
{
writer = new IndexWriter(Server.MapPath("index"), new Lucene.Net.Analysis.SimpleAnalyzer(), false);
IndexDirectory(writer, new FileInfo(Server.MapPath("doc")));
writer.Close();
}
public void IndexDirectory(IndexWriter writer, FileInfo file)
{
if (System.IO.Directory.Exists(file.FullName))
{
String[] files = System.IO.Directory.GetFileSystemEntries(file.FullName);
if (files != null)
{
for (int i = 0; i < files.Length; i++)
{
IndexDirectory(writer, new FileInfo(files[i]));
}
}
}
else if (file.Extension == ".txt" || file.Extension == ".htm" || file.Extension == ".html")
{
IndexFile(file, writer);
}
}
private void IndexFile(FileInfo file, IndexWriter writer)
{
try
{
Document doc = new Document();
txtListIndex.Text = txtListIndex.Text + "\n文件路径:" + file.FullName;
doc.Add(Field.Keyword("filename", Path.GetFileName(file.FullName).Replace(file.Extension,"")));
//doc.Add(Field.Text("contents", new StreamReader(file.FullName, System.Text.Encoding.Default)));
doc.Add(Field.Text("contents", file.FullName));
writer.AddDocument(doc);
}
catch (FileNotFoundException fnfe)
{
Response.Write(fnfe.Message);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
IndexSearcher searcher = new IndexSearcher(Server.MapPath("index"));
Query query = QueryParser.Parse("Linux", "filename", new Lucene.Net.Analysis.WhitespaceAnalyzer());
Hits hits = searcher.Search(query);
if (hits.Length() > 0)
{
for (int num = 0; num <= hits.Length() - 1; num++)
{
Document docNew = hits.Doc(num);
txtListIndex.Text = txtListIndex.Text + "\n" + docNew.Get("contents");
}
}
}