C# 读取文件内容

实现效果

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 均正常。

分词

全文检索分词可使用第三方分词实现,再加上搜索热度......

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容