Find and Replace in Word 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. 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)

1using System;
2using System.Text;
3using System.Linq;
4using GemBox.Document;
5
6class Sample
7{
8    [STAThread]
9    static void Main(string[] args)
10    {
11        // If using Professional version, put your serial key below.
12        ComponentInfo.SetLicense("FREE-LIMITED-KEY");
13
14        DocumentModel document = DocumentModel.Load("Reading.docx");
15
16        // Find and count text in document.
17        int documentCount = document.Content.Find("GemBox.Document").Count();
18
19        int counter = documentCount;
20
21        // Find and replace text in document.
22        foreach (ContentRange item in document.Content.Find("GemBox.Document").Reverse())
23            item.LoadText(string.Format("GBD ({0}/{1})", counter--, documentCount));
24
25        document.Save("Find and Replace.docx");
26    }
27}
1Imports System
2Imports System.Text
3Imports System.Linq
4Imports GemBox.Document
5
6Module Samples
7
8    Sub Main()
9
10        ' If using Professional version, put your serial key below.
11        ComponentInfo.SetLicense("FREE-LIMITED-KEY")
12
13        Dim document As DocumentModel = DocumentModel.Load("Reading.docx")
14
15        ' Find and count text in document.
16        Dim documentCount = document.Content.Find("GemBox.Document").Count()
17
18        Dim counter = documentCount
19
20        ' Find and replace text in document.
21        For Each item As ContentRange In document.Content.Find("GemBox.Document").Reverse()
22            item.LoadText(String.Format("GBD ({0}/{1})", counter, documentCount))
23            counter -= 1
24        Next
25
26        document.Save("Find and Replace.docx")
27
28    End Sub
29
30End Module

Check next sample or find out more about GemBox.Document and GemBox Software.