Find and Highlight Text in Word in C#, VB.NET

It is a little bothered to find specified text, phrase or sentence in a Word document with a large amount of contents. Therefore, the function, which enables users to find text in Word document quickly, is import and necessary. What's more, the found texts will be highlighted with a background color so that users can confirm the location more conveniently.

Spire.Doc for .NET, a professional .NET Word component, enables developers to find and highlight text in Word on their .NET applications. This guide focuses on showing the solution to find and highlight text in Word by using C#, VB.NET. Please have a look at the following screenshot, which presents the result you can get.

Find and Highlight Word Text

Download and install Spire.Doc for .NET. Load document which you want to find and highlight text. Then, invoke document.FindAllString(string, bool caseSensitive, bool wholeWord) method to find text “forming” in document. Next, save the found string in a TextSelection array. Use foreach sentence to set HighlightColor property for each selection in TextSelection array. Code as following

[C#]
using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;

namespace WordImage
{
    class ImageinWord
    {
        static void Main(string[] args)
        {
            //Create Document
            Document document = new Document();
            document.LoadFromFile(@"E:\Work\Documents\WordDocuments\References.docx");

            TextSelection[] text = document.FindAllString("forming", false, true);
            foreach (TextSelection seletion in text)
            {
                seletion.GetAsOneRange().CharacterFormat.HighlightColor = Color.Yellow;
            }

            document.SaveToFile("FindHighlight.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("FindHighlight.docx");
        }
    }
}
[VB.NET]
Imports System.Drawing
Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace WordImage
    Friend Class ImageinWord
        Shared Sub Main(ByVal args() As String)
            'Create Document
            Dim document As New Document()
            document.LoadFromFile("E:\Work\Documents\WordDocuments\References.docx")

            Dim text() As TextSelection = document.FindAllString("forming", False, True)
            For Each seletion As TextSelection In text
                seletion.GetAsOneRange().CharacterFormat.HighlightColor = Color.Yellow
            Next seletion

            document.SaveToFile("FindHighlight.docx", FileFormat.Docx)
            System.Diagnostics.Process.Start("FindHighlight.docx")
        End Sub
    End Class
End Namespace

Spire.Doc, a stand-alone Word component, which enables users to perform a wide range of Word document processing tasks with a fast speed such as generate, read, write and modify Word document in WPF, .NET and Silverlight without MS Word automation.