7 Useful Ways to Find and Replace Text in a Word Document Using C#
Tags: dotnet, csharp, productivity
Published: 2020-02-20 10:28:30

---
title: 7 Useful Ways to Find and Replace Text in a Word Document Using C#
published: true
date: 2020-02-19 12:25:37 UTC
tags: dotnet, csharp, productivity, 
canonical_url: https://www.syncfusion.com/blogs/post/7-useful-ways-to-find-and-replace-text-in-a-word-document-using-csharp.aspx
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/6w96u5x4ubp08ntxi7ws.png
---

Finding and replacing text in a Word document is an operation that saves a lot of manual work in modifying a document. In this article, we are going to learn how to find and replace text in Word documents programmatically in C# using [Syncfusion’s .NET Word Library (Essential DocIO)](https://www.syncfusion.com/word-framework/net/word-library). This does not require Microsoft Word or Office interop dependencies.

Syncfusion’s Word Library provides comprehensive APIs to find and replace text in a Word document with any desired text, image, hyperlink, paragraph, table, part of a document, or entire document. It provides options to find text by matching case and whole words. You can find each occurrence one by one or all the occurrences of a text at once in a document.

This feature saves you effort and time by helping you automatically find and replace a pattern of text in a Word document using [Regex](https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex).

You can save the resultant document as a Word document (DOCX, WordML, DOC), PDF, image, HTML, RTF, and more.

The seven ways to find and replace text in a Word document using C# are:

- [Find and replace text with other text.](#replace-text-with-other-text)
- [Find and replace text with an image.](#replace-text-with-image)
- [Find and replace a pattern of text with a merge field.](#replace-a-pattern-of-text-with-merge-fields)
- [Find and replace text with a table.](#replace-text-with-table)
- [Find and replace text with another document.](#replace-text-with-document)
- [Find and replace text extending to several paragraphs.](#replace-text-with-paragraph)
- [Find text in a document and highlight it.](#find-and-format-text)

## Find and replace text in a Word document with other text using C#

You can find text in a Word document and replace it with other text programmatically in C# using the Syncfusion Word Library. Unlike the **Find** method, the **Replace** method replaces all occurrences of the text. You can customize it to replace only the first occurrence of a text by setting the **ReplaceFirst** property of the **WordDocument** class to true.

The following code example illustrates how to replace all occurrences of a misspelled word with the correctly spelled word.

```csharp
//Creates new Word document instance for word processing.
using (WordDocument document = new WordDocument())
{
    //Opens the input Word document.
    Stream docStream = File.OpenRead(Path.GetFullPath(@"../../../Template.docx"));
    document.Open(docStream, FormatType.Docx);
    docStream.Dispose();
    //Finds all occurrences of a misspelled word and replaces with properly spelled word.
    document.Replace("Cyles", "Cycles", true, true);
    //Saves the resultant file in the given path.
    docStream = File.Create(Path.GetFullPath(@"Result.docx"));
    document.Save(docStream, FormatType.Docx);
    docStream.Dispose();
}
```

![Find a misspelled word and replace it with properly spelled word](https://www.syncfusion.com/blogs/wp-content/uploads/2020/02/Find-a-misspelled-word-and-replace-it-with-properly-spelled-word.png)<figcaption>Find a misspelled word and replace it with properly spelled word</figcaption>

The complete working example can be downloaded from this [GitHub location](https://github.com/SyncfusionExamples/Word-Find-and-Replace-Examples/tree/master/Find-and-replace-text).

## Find and replace text in Word document with an image using C#

You can find placeholder text in a Word document and replace it with any desired image programmatically in C# using the Syncfusion Word Library.

The following code example illustrates how to do this.

```csharp
//Creates new Word document instance for word processing.
using (WordDocument document = new WordDocument())
{
    //Opens the input Word document.
    Stream docStream = File.OpenRead(Path.GetFullPath(@"../../../Template.docx"));
    document.Open(docStream, FormatType.Docx);
    docStream.Dispose();
    //Finds all the image placeholder text in the Word document.
    TextSelection[] textSelections = document.FindAll(new Regex("^//(.*)"));
    for (int i = 0; i < textSelections.Length; i++)
    {
        //Replaces the image placeholder text with desired image.
        Stream imageStream = File.OpenRead(Path.GetFullPath(@"../../../" + textSelections[i].SelectedText + ".png"));
        WParagraph paragraph = new WParagraph(document);
        WPicture picture = paragraph.AppendPicture(imageStream) as WPicture;
        imageStream.Dispose();
        TextSelection newSelection = new TextSelection(paragraph, 0, 1);
        TextBodyPart bodyPart = new TextBodyPart(document);
        bodyPart.BodyItems.Add(paragraph);
        document.Replace(textSelections[i].SelectedText, bodyPart, true, true);
    }
    //Saves the resultant file in the given path.
    docStream = File.Create(Path.GetFullPath(@"Result.docx"));
    document.Save(docStream, FormatType.Docx);
    docStream.Dispose();
}
```

![Find text and replace it with desired image](https://www.syncfusion.com/blogs/wp-content/uploads/2020/02/Find-text-and-replace-it-with-desired-image.png)<figcaption>Find text and replace it with desired image</figcaption>

The complete working example can be downloaded from this [GitHub location](https://github.com/SyncfusionExamples/Word-Find-and-Replace-Examples/tree/master/Replace-text-with-image).

## Find and replace a pattern of text with a merge field using C#

Syncfusion’s Word Library allows you to find and replace a pattern of text in a Word document with merge fields programmatically in C# using [Regex](https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex).

The following code example illustrates how to create a mail merge template by replacing a pattern of text (enclosed within ‘«’ and ‘»’) in a Word document with the desired merge fields.

```csharp
//Creates new Word document instance for word processing.
using (WordDocument document = new WordDocument())
{
    //Opens the input Word document.
    Stream docStream = File.OpenRead(Path.GetFullPath(@"../../../Template.docx"));
    document.Open(docStream, FormatType.Docx);
    docStream.Dispose();
    //Finds all the placeholder text enclosed within '«' and '»' in the Word document.
    TextSelection[] textSelections = document.FindAll(new Regex("«([(?i)image(?-i)]*:*[a-zA-Z0-9 ]*:*[a-zA-Z0-9 ]+)»"));
    string[] searchedPlaceholders = new string[textSelections.Length];
    for (int i = 0; i < textSelections.Length; i++)
    {
        searchedPlaceholders[i] = textSelections[i].SelectedText;
    }
    for (int i = 0; i < searchedPlaceholders.Length; i++)
    {
        //Replaces the placeholder text enclosed within '«' and '»' with desired merge field.
        WParagraph paragraph = new WParagraph(document);
        paragraph.AppendField(searchedPlaceholders[i].TrimStart('«').TrimEnd('»'), FieldType.FieldMergeField);
        TextSelection newSelection = new TextSelection(paragraph, 0, paragraph.Items.Count);
        TextBodyPart bodyPart = new TextBodyPart(document);
        bodyPart.BodyItems.Add(paragraph);
        document.Replace(searchedPlaceholders[i], bodyPart, true, true, true);
    }
    //Saves the resultant file in the given path.
    docStream = File.Create(Path.GetFullPath(@"Result.docx"));
    document.Save(docStream, FormatType.Docx);
    docStream.Dispose();
}
```

![Find a pattern of text and replace it with merge fields](https://www.syncfusion.com/blogs/wp-content/uploads/2020/02/Find-a-pattern-of-text-and-replace-it-with-merge-fields.png)<figcaption>Find a pattern of text and replace it with merge fields</figcaption>

The complete working example can be downloaded from this [GitHub location](https://github.com/SyncfusionExamples/Word-Find-and-Replace-Examples/tree/master/Replace-text-with-merge-field).

## Find and replace text in a Word document with a table using C#

You can find placeholder text in a Word document and replace it with a table programmatically in C# using the Syncfusion Word Library.

The following code example illustrates how to do this.

```csharp
//Creates new Word document instance for word processing.
using (WordDocument document = new WordDocument())
{
    //Opens the input Word document.
    Stream docStream = File.OpenRead(Path.GetFullPath(@"../../../Template.docx"));
    document.Open(docStream, FormatType.Docx);
    docStream.Dispose();
    //Creates a new table.
    WTable table = new WTable(document);
    table.ResetCells(1, 6);
    table[0, 0].Width = 52f;
    table[0, 0].AddParagraph().AppendText("Supplier ID");
    table[0, 1].Width = 128f;
    table[0, 1].AddParagraph().AppendText("Company Name");
    table[0, 2].Width = 70f;
    table[0, 2].AddParagraph().AppendText("Contact Name");
    table[0, 3].Width = 92f;
    table[0, 3].AddParagraph().AppendText("Address");
    table[0, 4].Width = 66.5f;
    table[0, 4].AddParagraph().AppendText("City");
    table[0, 5].Width = 56f;
    table[0, 5].AddParagraph().AppendText("Country");
    //Imports data to the table.
    ImportDataToTable(table);
    //Applies the built-in table style (Medium Shading 1 Accent 1) to the table.
    table.ApplyStyle(BuiltinTableStyle.MediumShading1Accent1);
    //Replaces the table placeholder text with a new table
    TextBodyPart bodyPart = new TextBodyPart(document);
    bodyPart.BodyItems.Add(table);
    document.Replace("[Suppliers table]", bodyPart, true, true, true);
    //Saves the resultant file in the given path.
    docStream = File.Create(Path.GetFullPath(@"Result.docx"));
    document.Save(docStream, FormatType.Docx);
    docStream.Dispose();
}
```

![Find text and replace it with a desired table](https://www.syncfusion.com/blogs/wp-content/uploads/2020/02/Find-text-and-replace-it-with-a-desired-table.png)<figcaption>Find text and replace it with a desired table</figcaption>

The complete working example can be downloaded from this [GitHub location](https://github.com/SyncfusionExamples/Word-Find-and-Replace-Examples/tree/master/Replace-text-with-table).

## Find and replace text in Word document with another document using C#

The Syncfusion Word Library lets you find and replace text with another Word document programmatically in C#.

The following code example illustrates how to merge or combine Word documents by replacing text with another document (the content of a subheading).

```csharp
//Creates new Word document instance for word processing.
using (WordDocument document = new WordDocument())
{
    //Opens the input Word document.
    Stream docStream = File.OpenRead(Path.GetFullPath(@"../../../Template.docx"));
    document.Open(docStream, FormatType.Docx);
    docStream.Dispose();
    //Finds all the content placeholder text in the Word document.
    TextSelection[] textSelections = document.FindAll(new Regex(@"\[(.*)\]"));
    for (int i = 0; i < textSelections.Length; i++)
    {
        //Replaces the content placeholder text with desired Word document.
        docStream = File.OpenRead(Path.GetFullPath(@"../../../" + textSelections[i].SelectedText.TrimStart('[').TrimEnd(']') + ".docx"));
        WordDocument subDocument = new WordDocument(docStream, FormatType.Docx);
        docStream.Dispose();
        document.Replace(textSelections[i].SelectedText, subDocument, true, true);
        subDocument.Dispose();
    }
    //Saves the resultant file in the given path.
    docStream = File.Create(Path.GetFullPath(@"Result.docx"));
    document.Save(docStream, FormatType.Docx);
    docStream.Dispose();
}
```

![Find text and replace it with another Word document](https://www.syncfusion.com/blogs/wp-content/uploads/2020/02/Find-text-and-replace-it-with-another-Word-document.png)<figcaption>Find text and replace it with another Word document</figcaption>

The complete working example can be downloaded from this [GitHub location](https://github.com/SyncfusionExamples/Word-Find-and-Replace-Examples/tree/master/Replace-text-with-document).

## Find and replace text extending to several paragraphs in C#

Apart from finding text in a paragraph, you can also find and replace text that extends to several paragraphs in a Word document. You can find the first occurrence of the text that extends to several paragraphs by using the **FindSingleLine** method. Find the next occurrences of the text by using the **FindNextSingleLine** method. Similarly, you can replace text that extends to several paragraphs by using **ReplaceSingleLine** method.

The following code example illustrates how to replace text that extends to several paragraphs.

```csharp
//Creates new Word document instance for word processing.
using (WordDocument document = new WordDocument())
{
    //Opens the input Word document.
    Stream docStream = File.OpenRead(Path.GetFullPath(@"../../../Template.docx"));
    document.Open(docStream, FormatType.Docx);
    docStream.Dispose();
    docStream = File.OpenRead(Path.GetFullPath(@"../../../Source.docx"));
    WordDocument subDocument = new WordDocument(docStream, FormatType.Docx);
    docStream.Dispose();
    //Gets the content from another Word document to replace with.
    TextBodyPart replacePart = new TextBodyPart(subDocument);
    foreach (TextBodyItem bodyItem in subDocument.LastSection.Body.ChildEntities)
    {
        replacePart.BodyItems.Add(bodyItem.Clone());
    }
    string placeholderText = "Suppliers/Vendors of Northwind" + "Customers of Northwind"
        + "Employee details of Northwind traders" + "The product information"
        + "The inventory details" + "The shippers" + "Purchase Order transactions"
        + "Sales Order transaction" + "Inventory transactions" + "Invoices" + "[end replace]";
    //Finds the text that extends to several paragraphs and replaces it with desired content.
    document.ReplaceSingleLine(placeholderText, replacePart, false, false);
    subDocument.Dispose();
    //Saves the resultant file in the given path.
    docStream = File.Create(Path.GetFullPath(@"Result.docx"));
    document.Save(docStream, FormatType.Docx);
    docStream.Dispose();
}
```

![Find text that extends to several paragraphs and replace it](https://www.syncfusion.com/blogs/wp-content/uploads/2020/02/Find-text-that-extends-to-several-paragraphs-and-replace-it.png)<figcaption>Find text that extends to several paragraphs and replace it</figcaption>

The complete working example can be downloaded from this [GitHub location](https://github.com/SyncfusionExamples/Word-Find-and-Replace-Examples/tree/master/Find-and-replace-several-paragraphs).

## Find text in a Word document and format it using C#

Using the Syncfusion Word Library, you can find text in a Word document and format or highlight it programmatically in C#. You can find the first occurrence of text using the **Find** method. Find the next occurrences of the text using the **FindNext** method.

The following code example illustrates how to find all occurrences of a length of text and highlight it.

```csharp
//Creates new Word document instance for word processing.
using (WordDocument document = new WordDocument())
{
    //Opens the input Word document.
    Stream docStream = File.OpenRead(Path.GetFullPath(@"../../../Template.docx"));
    document.Open(docStream, FormatType.Docx);
    docStream.Dispose();
    //Finds all occurrence of the text in the Word document.
    TextSelection[] textSelections = document.FindAll("Adventure", true, true);
    for (int i = 0; i < textSelections.Length; i++)
    {
        //Sets the highlight color for the searched text as Yellow.
        textSelections[i].GetAsOneRange().CharacterFormat.HighlightColor = Color.Yellow;
    }
    //Saves the resultant file in the given path.
    docStream = File.Create(Path.GetFullPath(@"Result.docx"));
    document.Save(docStream, FormatType.Docx);
    docStream.Dispose();
}
```

![Find text and highlight it](https://www.syncfusion.com/blogs/wp-content/uploads/2020/02/Find-text-and-highlight-it.png)<figcaption>Find text and highlight it</figcaption>

Similarly, you can automate the process of highlighting or underlining any misspelled words in a Word document without using Microsoft Word.

The complete working example can be downloaded from this [GitHub location](https://github.com/SyncfusionExamples/Word-Find-and-Replace-Examples/tree/master/Find-and-highlight-text).

## Summary

Thank you for taking the time to read this blog. I hope it may have clarified finding and replacing text in Word documents using the [Syncfusion Word Library](https://www.syncfusion.com/word-framework/net). Take a moment to peruse the [documentation](https://help.syncfusion.com/file-formats/docio/working-with-find-and-replace), where you’ll find other options and features, all with accompanying code examples. Using the Library, you can create, edit, and merge Word documents, as well as convert them to [PDF](https://help.syncfusion.com/file-formats/docio/word-to-pdf), [image](https://help.syncfusion.com/file-formats/docio/word-to-image), [HTML](https://help.syncfusion.com/file-formats/docio/html), [RTF](https://help.syncfusion.com/file-formats/docio/rtf), and other formats.

If you are new to our Word Library (Essential DocIO), it is highly recommended that you follow our [Getting Started guide](https://help.syncfusion.com/file-formats/docio/getting-started).

Are you already a Syncfusion user? You can download the product setup [here](https://www.syncfusion.com/account/downloads/studio/). If you’re not yet a Syncfusion user, you can download a free, 30-day trial [here](https://www.syncfusion.com/downloads/fileformats/confirm).

If you have any questions about these features, please let us know in the comments below. You can also contact us through our [support forum](https://www.syncfusion.com/forums?_ga=2.160385213.108886952.1555906495-214292665.1551328372), [Direct-Trac](https://www.syncfusion.com/support/directtrac/?_ga=2.160385213.108886952.1555906495-214292665.1551328372), or [feedback portal](https://www.syncfusion.com/feedback/word). We are happy to assist you!

The post [7 Useful Ways to Find and Replace Text in a Word Document Using C#](https://www.syncfusion.com/blogs/post/7-useful-ways-to-find-and-replace-text-in-a-word-document-using-csharp.aspx) appeared first on [Syncfusion Blogs](https://www.syncfusion.com/blogs).