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)

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.
17        int documentCount = document.Content.Find("GemBox.Document").Count();
18
19        int counter = documentCount;
20
21        // Find text and load another text in its place.
22        foreach (ContentRange item in document.Content.Find("GemBox.Document").Reverse())
23            item.LoadText(string.Format("GBD ({0}/{1})", counter--, documentCount));
24
25        // Find and replace text.
26        document.Content.Replace(".NET", "C# / VB.NET");
27
28        document.Save("Find and Replace.docx");
29    }
30}
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.
16        Dim documentCount = document.Content.Find("GemBox.Document").Count()
17
18        Dim counter = documentCount
19
20        ' Find text and load another text in its place.
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        ' Find And replace text.
27        document.Content.Replace(".NET", "C# / VB.NET")
28
29        document.Save("Find and Replace.docx")
30
31    End Sub
32
33End Module

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