Find and Replace text in Word file with C# and VB.NET

With GemBox.Document, you can easily find all the parts of a document that contain the specified text or match the specified regular expression by using its Find method in C# or VB.NET code.

The following example demonstrates how to search for all occurrences of specified text in a document and replace them with any desired text by using LoadText method. The example also demonstrates the usage of Replace method for achieving the same task.

GemBox.Document can also replace the found content with any other content, as shown in the article Find & Replace text with Picture or Table.

Find and Replace in Word document
Upload your file (Drag file here)
using System.Linq;
using GemBox.Document;

class Program
{
    static void Main()
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        DocumentModel document = DocumentModel.Load("%InputFileName%");

        // Find and count text.
        int documentCount = document.Content.Find("GemBox.Document").Count();

        int counter = documentCount;

        // Find text and load another text in its place.
        foreach (ContentRange item in document.Content.Find("GemBox.Document").Reverse())
            item.LoadText(string.Format("GBD ({0}/{1})", counter--, documentCount));

        // Find and replace text.
        document.Content.Replace(".NET", "C# / VB.NET");

        document.Save("Find and Replace.%OutputFileType%");
    }
}
Imports System.Linq
Imports GemBox.Document

Module Program

    Sub Main()

        ' If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY")

        Dim document As DocumentModel = DocumentModel.Load("%InputFileName%")

        ' Find and count text.
        Dim documentCount = document.Content.Find("GemBox.Document").Count()

        Dim counter = documentCount

        ' Find text and load another text in its place.
        For Each item As ContentRange In document.Content.Find("GemBox.Document").Reverse()
            item.LoadText(String.Format("GBD ({0}/{1})", counter, documentCount))
            counter -= 1
        Next

        ' Find And replace text.
        document.Content.Replace(".NET", "C# / VB.NET")

        document.Save("Find and Replace.%OutputFileType%")

    End Sub

End Module

Check next example or download examples from GitHub.