文件内容搜索c#

2023-11-29

我正在尝试在我的应用程序中实现此功能。

File Content Search

就像在 Windows 中一样,我在搜索框中输入内容,如果在设置中选中了文件内容,则无论它是文本文件还是 pdf/word 文件,搜索都会返回包含搜索框中字符串的文件。

所以,我已经想出了一个用于文件和文件夹搜索的应用程序,它非常适合file content search适用于文本文件和Word 文件。我正在使用互操作字来处理字文件。

我知道,我可以用iTextSharp或其他一些第三方工具来对 pdf 文件执行此操作。但这并不能令我满意。我只是想知道windows是怎么做到的?或者如果其他人以不同的方式做到了?我只是不想使用任何第三方工具,但这并不意味着我不能。我只是想让我的应用程序保持轻量级,而不是用许多工具来抛弃它。


据我所知,如果没有安装第 3 方工具、软件或实用程序,则无法搜索 pdf 内容。例如,有 pdfgrep。但是,如果您设法以任何方式制作 C# 程序,我将包含一个第三方库来完成这项工作。

我在这个答案中为类似的事情做了一个解决方案在 C# 中根据 PDF 中的标签名称读取特定值,只需稍加调整,您就可以得到您想要的东西。唯一的问题是PdfClown,它是针对.net框架的,但另一方面它是开源的,免费的并且没有任何限制。但如果您正在寻找 .net core,您可能会找到一些免费(有限制)或付费的 pdf 库。

正如您在评论中所要求的,这里是一个在 pdf 侧页中查找文本的示例解决方案。我在代码中留下了注释:

//The found content
private List<string> _contentList;

//Search for content in a given pdf file
public bool SearchPdf(FileInfo fileInfo, string word)
{
    _contentList = new List<string>();
    ExtractPages(fileInfo.FullName);
    var content = string.Join(" ", _contentList);
    return content.Contains(word);
}

//Extract content for each page of given pdf file
private void ExtractPages(string filePath)
{
    using (var file = new File(filePath))
    {
        var document = file.Document;

        foreach (var page in document.Pages)
        {
            Extract(new ContentScanner(page));
        }
    }
}

//Extract content of pdf page and put the found result inside _contentList
private void Extract(ContentScanner level)
{
    if (level == null)
        return;

    while (level.MoveNext())
    {
        var content = level.Current;
        switch (content)
        {
            case ShowText text:
                {
                    var font = level.State.Font;
                    _contentList.Add(font.Decode(text.Text));
                    break;
                }
            case Text _:
            case ContainerObject _:
                Extract(level.ChildLevel);
                break;
        }
    }
}

现在让我们进行快速测试,因此我们假设您的所有发票都位于 c:\temp 文件夹中:

static void Main(string[] args)
{
    var program = new SearchPdfContent();

    DirectoryInfo d = new DirectoryInfo(@"c:\temp");
    FileInfo[] Files = d.GetFiles("*.pdf");
    var word = "Sushi";
    foreach (FileInfo file in Files)
    {
        var found = program.SearchPdf(file, word);
        if (found)
        {
            Console.WriteLine($"{file.FullName} contains word {word}");
        }
    }
}

就我而言,发票中有寿司一词:

c:\temp\invoice0001.pdf contains word Sushi

综上所述,这是一个解决方案的示例。您可以从这里将其提升到一个新的水平。祝您愉快。

我留下一些我搜索过的链接:

  • 搜索具有特定文件内容的文件
  • 如何搜索多个pdf文件的内容?
  • Windows 搜索 PDF 内容
  • https://superuser.com/questions/402673/how-to-search-inside-pdfs-with-windows-search
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

文件内容搜索c# 的相关文章

随机推荐