GemBox.Document is a .NET component that enables you to read, write, edit, convert, and print document files from your .NET applications using one simple API.

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.

Screenshot
Find and Replace in Word document

See the full code below, use Run Example to execute.

Upload your file(Drag files here)

Download a sample file

using System;
using System.Text;
using System.Linq;
using GemBox.Document;

class Sample
{
    [STAThread]
    static void Main(string[] args)
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        DocumentModel document = DocumentModel.Load("Reading.docx");

        // 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.docx");
    }
}
Imports System
Imports System.Text
Imports System.Linq
Imports GemBox.Document

Module Samples

    Sub Main()

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

        Dim document As DocumentModel = DocumentModel.Load("Reading.docx")

        ' 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.docx")

    End Sub

End Module

Check next sample.