实现效果
doc、docx、txt 文件内容检索
代码示例
添加第三方内库
Aspose.Words.dll
读取文件
上传文件时,将文件内容读取成字符串存储
/// 读文件
/// </summary>
/// <param name="officeByte">文件内容</param>
/// <param name="fileType">.doc / .docx / .txt</param>
/// <returns>文件内容</returns>
public string ReadFile(byte[] officeByte, string fileType)
{
try
{
string content = "文件格式不支持检索";
Stream stream = new MemoryStream(officeByte);
Aspose.Words.Document doc = new Aspose.Words.Document(stream);
if (fileType == ".doc" || fileType == ".docx")
{
string filePath = HttpContext.Current.Server.MapPath("SingleTable\\upfiles\\temp.doc");
doc.Save(filePath, Aspose.Words.SaveFormat.Doc);
content = doc.GetText();
}
else if (fileType == ".txt")
{
string filePath = HttpContext.Current.Server.MapPath("SingleTable\\upfiles\\temp.txt");
doc.Save(filePath, Aspose.Words.SaveFormat.Text);
StreamReader sr = new StreamReader(filePath, GetEncoding(filePath));
content = sr.ReadToEnd().ToString();
sr.Close();
}
return content;
}
catch (Exception e)
{
return "对不起,本文没有发现!可能是从服务器上删除的。";
}
}
/// 读文件
/// </summary>
/// <param name="filePath">文件路径</param>
/// <param name="fileType">.doc / .docx / .txt</param>
/// <returns>文件内容</returns>
public string ReadFile(string filePath, string fileType)
{
try
{
string content = "文件格式不支持检索";
filePath = HttpContext.Current.Server.MapPath(filePath);
if (fileType == ".doc" || fileType == ".docx")
{
Aspose.Words.Document doc = new Aspose.Words.Document(filePath);
content = doc.GetText();
}
else if (filePath == ".txt")
{
StreamReader sr = new StreamReader(filePath, GetEncoding(filePath));
content = sr.ReadToEnd().ToString();
sr.Close();
}
return content;
}
catch (Exception e)
{
return "对不起,本文没有发现!可能是从服务器上删除的。";
}
}
组合查询条件(空格分词)
string strFieldValue = data_fieldValue[j].ToString().Trim();
strFieldValue = Regex.Replace(strFieldValue, @"\s+", " ");
message.Append(" ( ");
foreach (string strValue in strFieldValue.Split(' '))
{
message.Append(" fileName like '%" + strValue + "%' or");
}
message.Remove(message.Length - 2, 2);
message.Append(" ) and");
注意事项
乱码
Txt 默认格式为 ANSI,读取会出现乱码,Unicode、UTF-8 均正常。
分词
全文检索分词可使用第三方分词实现,再加上搜索热度......
网友评论