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

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

Upload your file(Drag files here)

Download an input file

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

class Sample
    static void Main(string[] args)
        // If using Professional version, put your serial key below.

        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.

        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

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

        document.Save("Find and Replace.docx")

    End Sub

End Module