How to find a specific text in DOCX document using C# and .NET

  1. Add SautinSoft.Document from Nuget.
  2. Load a DOCX document.
  3. Find a specific text.
  4. Count all matches.

How to count how many times a specific text 'Tom' appears in the document.

Complete code

using System;
using System.IO;
using System.Linq;
using SautinSoft.Document;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get your free 100-day key here:   
            // https://sautinsoft.com/start-for-free/

            FindText();
        }
        /// <summary>
        /// Find a specific text in DOCX document.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/find-text-in-docx-document-net-csharp-vb.php
        /// </remarks>
        static void FindText()
        {
            string filePath = @"..\..\..\example.docx";
            DocumentCore dc = DocumentCore.Load(filePath);
            string searchText = "document";
            int count = dc.Content.Find(searchText).Count();

            Console.WriteLine("The text: \"" + searchText + "\" - was found " + count.ToString() + " time(s).");
            Console.ReadKey();
        }
    }
}

Download

Imports System
Imports System.IO
Imports System.Linq
Imports SautinSoft.Document

Module Sample
    Sub Main()
        FindText()
    End Sub
    ''' Get your free 100-day key here:   
    ''' https://sautinsoft.com/start-for-free/
    ''' <summary>
    ''' Find a specific text in DOCX document.
    ''' </summary>
    ''' <remarks>
    ''' Details: https://sautinsoft.com/products/document/help/net/developer-guide/find-text-in-docx-document-net-csharp-vb.php
    ''' </remarks>
    Sub FindText()
        Dim filePath As String = "..\..\..\example.docx"
        Dim dc As DocumentCore = DocumentCore.Load(filePath)
        Dim searchText As String = "document"
        Dim count As Integer = dc.Content.Find(searchText).Count()

        Console.WriteLine("The text: """ & searchText & """ - was found " & count.ToString() & " time(s).")
        Console.ReadKey()
    End Sub
End Module

Download


If you need a new code example or have a question: email us at support@sautinsoft.com or ask at Online Chat (right-bottom corner of this page) or use the Form below:



Questions and suggestions from you are always welcome!

We are developing .Net components since 2002. We know PDF, DOCX, RTF, HTML, XLSX and Images formats. If you need any assistance with creating, modifying or converting documents in various formats, we can help you. We will write any code example for you absolutely free.