IRONSOFTWAREHOME

How to Replace Text in a Word Document with C#

Curtis Chau
Curtis Chau
Updated: August 2, 2026

IronWord enables C# developers to programmatically find and replace text in Word documents without Microsoft Office Interop, providing a solution for automating document updates, personalizing templates, and bulk content management.

Automating text replacement in Word documents is a common need, whether you're personalizing templates, updating reports, or managing content in bulk. IronWord is a C# library that makes this task straightforward, handling everything from simple find-and-replace operations to complex document processing workflows.

IronWord manipulates Word documents directly, without relying on Microsoft Office Interop. This means you don't need Word installed on your server, resulting in a faster, more reliable, and scalable solution for back-end processes and web applications. This independence from Microsoft Office makes IronWord particularly valuable for cloud deployments, containerized applications, and automated document processing pipelines.

In this how-to guide, we'll walk through comprehensive code examples to show you how to find and replace text in any Word document. Whether you're working with simple text replacements or need to handle complex document structures with multiple paragraphs and formatting, IronWord provides the tools you need.

Quickstart: Replace Text in Word Documents Easily

This guide demonstrates how to replace text in a Word document using IronWord. With just a few lines of C#, you can load a DOCX file, replace specified text, and save the updated document. This process works without Microsoft Office Interop, making it ideal for backend processes and web applications.

  1. 1Install IronWord with NuGet Package Manager

    PM > Install-Package IronWord

  2. 2Copy and run this code snippet.

    WordDocument doc = new WordDocument("sample.docx");
    doc.ReplaceText("oldText", "newText");
    doc.SaveAs("updated.docx");
    C#
  3. 3Deploy to test on your live environment

    Start using IronWord in your project today with a free trial
    arrow pointer

How Do I Replace Text in a Word Document?

Replacing text within a Word Document is intuitive with IronWord. First, we load an existing document using the WordDocument constructor. Then, we access the Paragraphs property and use the ReplaceText method on a specific paragraph. This approach gives you fine-grained control over which parts of your document to modify.

The ReplaceText method takes two string parameters: the text to find and the text to replace it with. This method performs a complete replacement of all matching instances within the selected paragraph, making it perfect for scenarios like updating product names, changing dates, or personalizing customer information.

Tips: The ReplaceText method is case-sensitive and replaces all instances of the string within the selected paragraph.

When working with the Paragraphs collection, it's important to understand how IronWord structures document content. Each paragraph in a Word document is represented as an individual element in the collection, allowing you to target specific sections of your document with precision.

Tips: All object lists used in this example follow zero-based indexing.

What Does the Input Document Look Like?

In this example, we'll use this sample Word document that contains two paragraphs, both with the text "old text". This simple structure demonstrates how text replacement works at the paragraph level.

Sample Word document showing 'old text' content before replacement

How Do I Write the Replacement Code?

Here's the code to replace the first paragraph's "old text" with "new text". Notice how we use index notation to target specific paragraphs, giving us precise control over which content gets modified:

using IronWord;

// Open existing Word
WordDocument doc = new WordDocument("sample.docx");

// Replace the first paragraph's old text with new text
doc.Paragraphs[0].ReplaceText("old text", "new text");

// Save updated Word Document
doc.SaveAs("updated.docx");

The code above demonstrates the simplicity of text replacement with IronWord. By loading the document, targeting a specific paragraph, and calling ReplaceText, you can modify document content in just a few lines of code. This approach is more straightforward than traditional Office Interop methods.

What Does the Output Look Like?

Word document output showing 'new text' in first paragraph and 'old text' in second paragraph after replacement operation

As you can see in the output file, only the first paragraph's text has been changed, while the second remains untouched. This selective replacement capability is crucial when you need to update specific sections without affecting the entire document.

How Do I Replace Multiple Text Occurrences?

To replace every occurrence of a word throughout the entire document, loop through the Paragraphs collection and apply the ReplaceText method to each one. This approach ensures that no instance of your target text is missed, regardless of where it appears in the document.

We'll use the same sample.docx file as before. If the text to be replaced isn't found in a paragraph, no operation is performed, and the loop continues to the next paragraph. This fail-safe behavior means you don't need to worry about checking if text exists before attempting replacement.

Please note: If the text you wish to replace is not found, no operations will be performed.

What Code Do I Need for Multiple Replacements?

Here's the code to replace all occurrences of "old text" with "new text" throughout the entire document:

using IronWord;

// Open existing Word
WordDocument doc = new WordDocument("sample.docx");

// Loop through each paragraph to find and replace text
for (int i = 0; i < doc.Paragraphs.Count; i++)
{
    // Replace all occurrences of "old text" with "new text" in the current paragraph
    doc.Paragraphs[i].ReplaceText("old text", "new text");
}

// Save updated Word Document
doc.SaveAs("updated.docx");

This looping approach provides complete coverage of your document. By iterating through every paragraph, you ensure that all instances of your target text are replaced. This method is particularly useful for bulk updates, such as changing company names, updating terminology, or applying consistent formatting across a document.

What Will the Document Look Like After Multiple Replacements?

Word document output showing two lines of 'new text' after multiple text replacement operation

As you can see from this updated Word Document, both paragraphs have been replaced with "new text". This demonstrates the effectiveness of the looping approach for comprehensive text replacement.

How Can I Verify Text Exists Before Replacing?

If you need to verify that text exists before performing an operation, use the FindText method. This method searches the entire document and returns the first TextContent that matches the search query. This verification step can be useful when you need to confirm the presence of specific content before making changes or when building conditional logic based on document content.

The FindText method is particularly valuable in scenarios where:

  • You need to log which documents contain specific text
  • You want to perform different actions based on whether text is found
  • You're building a document validation system
  • You need to generate reports on document content

Below is an example of searching for the old text in the Word document mentioned above.

What Code Do I Use to Find Text?

using IronWord;
using System;

// Open existing Word
WordDocument doc = new WordDocument("sample.docx");

// Returns the first TextContent element that contains the specified text.
Console.WriteLine(doc.FindText("old text"));

This code demonstrates the simplicity of text searching with IronWord. The FindText method returns a TextContent object if the text is found, or null if it isn't, making it easy to implement conditional logic based on the search results.

What Does the Find Text Result Show?

Visual Studio Debug console displaying 'old_text' output from FindText operation

As you can see, it returned the matching text, confirming that the search term exists in the document. This verification capability is essential for building robust document processing applications that need to handle various content scenarios.

Warning: If FindText returns nothing, the text does not exist in the document. Ensure your search term is spelled correctly and matches the case of the text in the document.

To populate MERGEFIELD placeholders from a data source such as a dictionary, DataTable, or DataSet instead of replacing literal strings, see how to mail merge Word documents in C#.

Best Practices for Text Replacement

When working with text replacement in Word documents, consider these best practices:

  1. Case Sensitivity: ReplaceText is case-sensitive. Convert text to consistent case for case-insensitive replacement.
  2. Performance Optimization: Batch replacements and save once to reduce I/O operations and improve performance.
  3. Error Handling: Implement error handling for locked, corrupted, or unexpected document content.
  4. Backup Strategy: Create backups before bulk replacements, especially in production environments.
  5. Memory Management: Dispose of document objects properly when processing multiple documents to prevent memory leaks.

IronWord's straightforward API makes implementing these best practices simple, allowing you to build robust document processing solutions with confidence.

Frequently Asked Questions

How can I replace text in a Word document using C#?

You can replace text in a Word document using IronWord by loading the document, utilizing the ReplaceText method to specify old and new text, and then saving the document. This eliminates the need for Microsoft Office Interop.

What are the benefits of using IronWord for text replacement?

IronWord offers benefits such as independence from Microsoft Office, faster processing, scalability, and compatibility with cloud and containerized applications, making it a suitable choice for automated document processing.

How does IronWord handle multiple text replacements in a document?

To replace multiple occurrences of a text in a Word document, you can loop through each paragraph using the Paragraphs collection and apply the ReplaceText method for comprehensive text replacement.

What is the ReplaceText method in IronWord?

The ReplaceText method is a function in IronWord that allows developers to find and replace specified text within a Word document. It is versatile and can be applied to specific paragraphs or the entire document.

Is the text replacement feature in IronWord case-sensitive?

Yes, the ReplaceText method in IronWord is case-sensitive, so it requires an exact match of text to perform replacements. You may need to adjust the text case for consistent results.

Do you need Microsoft Office installed to use IronWord?

No, you do not need Microsoft Office installed to use IronWord. IronWord functions independently, allowing operations on Word documents without relying on Office Interop.

Can IronWord find text in a document before replacing it?

Yes, IronWord can search for text using the FindText method, which returns a TextContent object if the text is found, aiding in conditional logic before text replacement.

What debugging features does IronWord offer for text replacement?

IronWord provides methods like FindText for locating text, which helps confirm the presence of text prior to replacement, essential for debugging document processing logic.

How can I ensure all target text is replaced in a document with IronWord?

By iterating through each paragraph using a loop and applying the ReplaceText method, you ensure comprehensive replacement of all target text instances in the document with IronWord.

What best practices should be followed when replacing text with IronWord?

Best practices include ensuring case sensitivity, optimizing performance by batching replacements, implementing error handling, creating backups, and managing memory efficiently.

Curtis Chau
Technical Writer

Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.

...
Read More

Ready to Get Started?

Nuget Downloads 56,401Version:2026.9just released

Get your free 30-day Trial Key instantly.
No credit card or account creation required
C# NuGet Library for PDF
Install with NuGet

Version: 2026.9

PM > Install-Package IronWord
nuget.org/packages/IronWord/
  1. In Solution Explorer, right-click References, Manage NuGet Packages
  2. Select Browse and search "IronWord"
  3. Select the package and install
C# PDF DLL
Download DLL

Version: 2026.9

  1. Download and unzip IronWord to a location such as ~/Libs within your Solution directory
  2. In Visual Studio Solution Explorer, right click References. Select Browse, "IronWord.dll"

Licenses from $999

Key in blue circle

Get your free 30-day Trial Key instantly.

Your trial license will be sent to your email address

No limitations. 100% unlocked. No credit card.

bullet_checkedNo credit card or account creation requiredNo limitations. 100% unlocked. No credit card.
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
Book your free Live Demo
Booking Badge

Trusted by Millions of Engineers Worldwide

Iron Software's customer logos
Get Your No-Obligation Consult
Complete the form below or email sales@ironsoftware.com
Your details will always be kept confidential.
Trusted by Millions of Engineers Worldwide
Iron Software's customer logos
Get your free 30-day Trial Key instantly.
No credit card or account creation required