C#/VB.NET: Apply Formatting to Characters in Word
Character formatting is used to change the appearance of individual words or phrases. Formatted text can direct the reader's attention to select sections of a document and highlight key information. There are quite a lot of forms of characters formatting that you can use in Word. In this article, you will learn how to apply various types of formatting to characters in Word in C# and VB.NET using Spire.Doc for .NET.
- Font Name
- Font Size
- Font Color
- Highlight Color
- Bold
- Italic
- Underline
- Strikethrough
- Border
- Shadow Effect
- Emphasis Mark
- Subscript and Superscript
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Apply Formatting to Characters in Word in C# and VB.NET
In order to apply formatting to a piece of text, you need to get the text in a TextRange and then format the characters within the TextRange through the CharacterFormat property. The following are the detailed steps.
- Create a Document object.
- Add a section to the document using Document.AddSection() method.
- Add a paragraph to the section using Section.AddParagraph() method.
- Append text to the paragraph using Paragraph.AppendText() method and return a TextRange object.
- Apply formatting such as font name, font size, border and highlight color to the characters within the text range through TextRange.CharacterFormat property.
- Save the document to a Word file using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;
namespace ApplyFormattingToCharacters
{
class Program
{
static void Main(string[] args)
{
//Create a Document object
Document document = new Document();
//Add a section
Section sec = document.AddSection();
//Add a paragraph
Paragraph paragraph = sec.AddParagraph();
paragraph.AppendText("Here is a paragraph with various character styles. This is ");
//Append text to the paragraph and return a TextRange object
TextRange tr = paragraph.AppendText("text with strikeout");
//Set the character format to strikeout via TextRange object
tr.CharacterFormat.IsStrikeout = true;
//Apply shadow effect to text
paragraph.AppendText(". This is ");
tr = paragraph.AppendText("text with shadow");
tr.CharacterFormat.IsShadow = true;
//Set font size
paragraph.AppendText(". This is ");
tr = paragraph.AppendText("text in a large font size");
tr.CharacterFormat.FontSize = 20;
//Set font name
paragraph.AppendText(". This is ");
tr = paragraph.AppendText("text in the font of Arial Black");
tr.CharacterFormat.FontName = "Arial Black";
//Set font color
paragraph.AppendText(". This is ");
tr = paragraph.AppendText("text in red");
tr.CharacterFormat.TextColor = Color.Red;
//Apply bold & italic to text
paragraph.AppendText(". This is ");
tr = paragraph.AppendText("text in bold & italic");
tr.CharacterFormat.Bold = true;
tr.CharacterFormat.Italic = true;
//Apply underline to text
paragraph.AppendText(". This is ");
tr = paragraph.AppendText("underlined text");
tr.CharacterFormat.UnderlineStyle = UnderlineStyle.Single;
//Apply background color to text
paragraph.AppendText(". This is ");
tr = paragraph.AppendText("text with highlight color");
tr.CharacterFormat.HighlightColor = Color.Green;
//Apply border to text
paragraph.AppendText(". This is ");
tr = paragraph.AppendText("text with border");
tr.CharacterFormat.Border.BorderType = Spire.Doc.Documents.BorderStyle.Single;
tr.CharacterFormat.Border.Color = Color.Black;
//Apply emphasis mark to text
paragraph.AppendText(". This is ");
tr = paragraph.AppendText("text with emphasis mark");
tr.CharacterFormat.EmphasisMark = Emphasis.DotBelow;
//Apply superscript to text
paragraph.AppendText(". This is a math formula: a");
tr = paragraph.AppendText("2");
tr.CharacterFormat.SubSuperScript = SubSuperScript.SuperScript;
paragraph.AppendText(" + b");
tr = paragraph.AppendText("2");
tr.CharacterFormat.SubSuperScript = SubSuperScript.SuperScript;
paragraph.AppendText(" = c");
tr = paragraph.AppendText("2");
tr.CharacterFormat.SubSuperScript = SubSuperScript.SuperScript;
paragraph.AppendText(".");
//Save to file
document.SaveToFile("SetCharacterFormat.docx", FileFormat.Docx);
}
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
C#/VB.NET: Apply Emphasis Marks in Word
The emphasis mark is used in Word documents to emphasize words and make them more noticeable. It is usually a dot or a circle placed above or under the emphasized words. However, manually selecting words and applying emphasis marks on them takes a lot of work. Fortunately, Spire.Doc for .NET provides a much easier way to apply emphasis marks by codes. This article will show you how to apply emphasis marks to text in Word documents using Spire.Doc for .NET.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Apply Emphasis Mark to Specified Text
The detailed steps are as follows:
- Create a Document instance.
- Load the Word document from disk using Document.LoadFromFile() method.
- Find the text you need to emphasize using Document.FindAllString() method.
- Apply emphasis mark to the found text through CharacterFormat.EmphasisMark property.
- Save the document to another Word file using Document.SaveToFile() method.
- C#
- VB.NET
using System;
using Spire.Doc;
using Spire.Doc.Documents;
namespace applyemphasismark
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document document = new Document();
//Load the Word document from disk
document.LoadFromFile(@"D:\testp\test.docx");
//Find text you want to emphasize
TextSelection[] textSelections = document.FindAllString("Spire.Doc for .NET", false, true);
//Apply emphasis mark to the found text
foreach (TextSelection selection in textSelections)
{
selection.GetAsOneRange().CharacterFormat.EmphasisMark = Emphasis.Dot;
}
//Save the document to another Word file
string output = "ApllyEmphasisMark.docx";
document.SaveToFile(output, FileFormat.Docx);
}
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
C# Regex Replace: Replace Text in Word Document [Tutorial]

When working with Word templates, it's common to replace specific placeholders with real content—like names, dates, or even company logos. Manually updating each instance may take lots of effort and time. Fortunately, you can automate this process using code. In this tutorial, we'll show you how to use C# regex replace to find and replace text in Word documents. You'll learn how to apply regular expressions across the entire document, target specific paragraphs, and even replace matched text with images.
- Before We Start: Install Word Library
- Replace Text in an Entire Word Document
- Replace Text within Specific Paragraph in C#
- Replace Regex Matches with Images
- Replace Text with Regex in VB.NET
- Conclusion
Before We Start: Install Word Library
To make this task easier, we recommend using Spire.Doc for .NET — a powerful Word library designed to automate common document operations such as reading, editing, and converting Word files. With Spire.Doc, performing a C# regex replace in Word documents can be done in just a few lines of code.
You can install the library via NuGet with the following command:
PM> Install-Package Spire.Doc
Alternatively, you can download the Spire.Doc package and install it with custom settings. A free version is also available, ideal for small projects or evaluation purposes.
Use Regex to Replace Text in an Entire Word Document
Let's start with the most common scenario — replacing text throughout the entire Word document. You can use regular expressions to match all patterns like #name or #tel, then replace them with actual values such as a person's name or phone number.
With the help of the Document.Replace() method provided by Spire.Doc, this task becomes incredibly simple. Here's a step-by-step explanation along with sample code to show how to replace text using regex in C#.
Code example - replacing #name with "May" in the entire Word document using C#:
using Spire.Doc;
using System.Text.RegularExpressions;
namespace FindText
{
class Program
{
static void Main(string[] args)
{
// Create an object of Document class and load a Word document
Document doc = new Document();
doc.LoadFromFile("/input/replace template.docx");
// Set the regular expression
Regex regex = new Regex(@"#\w+\b");
// Replace all matches with "May"
doc.Replace(regex, "May");
// Save the document
doc.SaveToFile("/output/replacealloccurences.docx", FileFormat.Docx2013);
}
}
}
Here is a comparison preview of the results before and after using regex to replace text in C#: 
Steps Explained:
- Create a Document instance and load a Word document from files.
- Set the regular expression.
- Replace all matches in the document with Documet.Replace() method.
- Save the updated document.
Apply Regex Replace to a Specific Paragraph in C#
Replacing text across the entire document may seem straightforward, but how can we achieve the same result within a specific paragraph? When you need more precise control, such as performing regex replace only within a paragraph range, you can retrieve the paragraph text and reset its content manually. In code, this means using regular expressions to locate matches within the target paragraph, remove the original text, and insert the replacement.
Let’s first look at a real-world code example — we’ll break down the detailed steps right after.
Code example - replacing #name with "Lily" in the first paragraph using regular expression:
using Spire.Doc;
using Spire.Doc.Documents;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
// Create a Document object and load a template
Document doc = new Document();
doc.LoadFromFile("/input/replace template.docx");
Regex regex = new Regex(@"#\w+\b");
// Get the first paragraph
Paragraph para = doc.Sections[0].Paragraphs[0];
string originalText = para.Text;
if (regex.IsMatch(originalText))
{
string newText = regex.Replace(originalText, "Lily");
// Clear the content and append the new text
para.ChildObjects.Clear();
para.AppendText(newText);
}
// Save the updated document
doc.SaveToFile("/output/replacefirstpara.docx", FileFormat.Docx2013);
}
}
Here is a before-and-after comparison of using regular expressions in C# to replace text in the first paragraph: 
Detailed steps explained:
- Create a Document object and load the Word file.
- Access the target paragraph using Sections[].Paragraphs[] property.
- Get the original text from the paragraph.
- Use a regular expression to find and replace matching text.
- Clear the original content and append the updated text to the paragraph.
- Save the modified document.
Replace Regex Matches with Images in Word Using C#
Now that we’ve covered how to replace text in the entire document or within a single paragraph, let’s move on to something more advanced—replacing text with images. This is often used in practical scenarios like generating reports or company brochures. For instance, you might want to replace a placeholder such as [logo] with your company’s actual logo.
With the help of C# regex replace and Spire.Doc’s image insertion APIs, this task can also be automated. Let’s take a look at a real code example first, then we’ll explain how it works.
Code example – replacing [avatar] with an image:
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Text.RegularExpressions;
namespace RegexReplaceWithImage
{
class Program
{
static void Main(string[] args)
{
// Create a Document object and load a Word file from disk
Document document = new Document();
document.LoadFromFile(@"\input\replace template.docx");
// Define a regular expression to match placeholders
Regex regex = new Regex(@"\[\w+\]", RegexOptions.IgnoreCase);
// Find all matches in the document that match the pattern
TextSelection[] selections = document.FindAllPattern(regex);
// Loop through each matched placeholder
foreach (TextSelection selection in selections)
{
// Create a picture object and load the image from disk
DocPicture pic = new DocPicture(document);
pic.LoadImage(@"\avatar-1.png");
// Get the matched text as a single text range
TextRange textRange = selection.GetAsOneRange();
// Get the index of the text range in its parent paragraph
int index = textRange.OwnerParagraph.ChildObjects.IndexOf(textRange);
// Insert the image at the matched position
textRange.OwnerParagraph.ChildObjects.Insert(index, pic);
// Remove the original placeholder text
textRange.OwnerParagraph.ChildObjects.Remove(textRange);
}
// Save the modified document to disk
document.SaveToFile(@"\output\ReplaceTextWithImage.docx", FileFormat.Docx2016);
document.Close();
}
}
}
Here is a before-and-after comparison of replacing text with an image using regex in C#: 
Detailed steps explained:
- Create an object of Document class and read a Word document.
- Define a regular expression to match target content.
- Find all occurrences using Document.FindAllPattern() method.
- Loop through the collection of matches.
- Create a DocPicture instance and load an image.
- Get the matched text as a text range and retrieve its index in the parent paragraph.
- Insert the image at the position and remove the original text.
- Save the Word document as a new file.
Replace Text with Regex in VB.NET
If you're working with VB.NET instead of C#, you can achieve the same result using regular expressions to search and replace text throughout a Word document. The approach is similar—load the file, apply a regex pattern, and update the content. Here's a simple example to get you started.
Imports Spire.Doc
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim doc As New Document()
doc.LoadFromFile("/input/replace template.docx")
Dim regex As New Regex("#\w+\b")
doc.Replace(regex, "Lena")
doc.SaveToFile("/output/regexreplace.docx", FileFormat.Docx2013)
End Sub
End Module
Above is the VB.NET code for replacing text throughout an entire Word document using regular expressions.
If you need to perform other tasks, such as replacing text in specific paragraphs or replacing text with images, you can easily convert the C# code examples into VB.NET using the C# Code ⇆ VB.NET Code Converter — a handy tool developed by the Spire.Doc team.
The Conclusion
With the help of regular expressions, replacing text or even inserting images in Word documents using C# becomes a smooth and efficient process. Whether you're working on templates, reports, or personalized documents, this approach saves time and reduces manual work. Ready to try it out? Download Spire.Doc and get started with a free 30-day trial license—perfect for evaluation and small projects.
C#/VB.NET: Change Text Case to All Capitals in Word
Capitals are quite suitable for stressing texts in Word. A paragraph written with capitalized letters is easy to notice, and capitalized letters imply the importance of the paragraph. This article teaches you the method of changing the case of existing text to all capitals with Spire.Doc for .NET by programming.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Change the Case of a Specified Paragraph to All Capitals
The detailed steps are as follows:
- Create an object of Document and load a sample Word document from file using Document.LoadFromFile() method.
- Get the second paragraph using Document.Sections[].Paragraph[] property and set its characters to AllCaps through TextRange.CharacterFormat.AllCaps property.
- Get the third paragraph using Document.Sections[].Paragraph[] property and set its characters to IsSmallCaps by TextRange.CharacterFormat.IsSmallCaps property.
- Save the document to a new Word file using Document.SaveToFile() method.
Note: AllCaps means to capitalize all the letters and set them to the same size, and IsSmallCaps means to capitalize all the letters but set the original majuscules bigger than the minuscules.
- C#
- VB.NET
using System;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace changecase
{
class Program
{
static void Main(string[] args)
{
//Create a new document and load from file
string input = @"D:\testp\test.docx"; ;
Document doc = new Document();
doc.LoadFromFile(input);
TextRange textRange;
//Get the second paragraph and set its characters to AllCaps
Paragraph para1 = doc.Sections[0].Paragraphs[2];
foreach (DocumentObject obj in para1.ChildObjects)
{
if (obj is TextRange)
{
textRange = obj as TextRange;
textRange.CharacterFormat.AllCaps = true;
}
}
//Get the third paragraph and set its characters to IsSmallCaps
Paragraph para2 = doc.Sections[0].Paragraphs[3];
foreach (DocumentObject obj in para2.ChildObjects)
{
if (obj is TextRange)
{
textRange = obj as TextRange;
textRange.CharacterFormat.IsSmallCaps = true;
}
}
//Save the document to a new Word file
string output = "ChangeCase.docx";
doc.SaveToFile(output, FileFormat.Docx2013);
}
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
C#: Extract or Update Text in Textbox in Word
Textboxes in Microsoft Word are versatile tools that enhance document layout and design. They allow users to position text independently of the main text flow, making it easier to create visually appealing documents. In some cases, you may need to extract text from textboxes for repurposing, or update the text inside a textbox to ensure clarity and relevance.
In this article, you will learn how to extract or update text in a textbox in a Word document using C# with Spire.Doc for .NET.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Extract Text from Textbox in a Word Document
Using Spire.Doc for .NET, you can access a specific text box in a document with the Document.TextBoxes[index] property. Iterate through the text box's child objects to check if each one is a paragraph or a table. For paragraphs, retrieve the text using the Paragraph.Text property. For tables, loop through the cells to extract text from each cell.
The steps to extract text from a textbox in a Word document are as follows:
- Create a Document object.
- Load a Word file using Document.LoadFromFile() method.
- Get a specific textbox using Document.TextBoxes[index] property
- Iterate through the child objects of the textbox.
- Determine if a child object if a paragraph. If yes, get the text from the paragraph using Paragraph.Text property.
- Determine if a child object if a table. If yes, get the text from the table using ExtractTextFromTable() method.
- C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace ExtractTextFromTextbox
{
class Program
{
static void Main(string[] args)
{
// Create a Document object
Document document = new Document();
// Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.docx");
// Get a specific textbox
TextBox textBox = document.TextBoxes[0];
// Create a StreamWriter to write extracted text to a txt file
using (StreamWriter sw = File.CreateText("result.txt"))
{
// Iterate though child objects of the textbox
foreach (DocumentObject objt in textBox.ChildObjects)
{
// Determine if the child object is a paragraph
if (objt.DocumentObjectType == DocumentObjectType.Paragraph)
{
// Write paragraph text to the txt file
sw.Write((objt as Paragraph).Text);
}
// Determine if the child object is a table
if (objt.DocumentObjectType == DocumentObjectType.Table)
{
// Extract text from table to the txt file
ExtractTextFromTable(objt as Table, sw);
}
}
}
}
// Extract text from a table
static void ExtractTextFromTable(Table table, StreamWriter sw)
{
for (int i = 0; i < table.Rows.Count; i++)
{
TableRow row = table.Rows[i];
for (int j = 0; j < row.Cells.Count; j++)
{
TableCell cell = row.Cells[j];
foreach (Paragraph paragraph in cell.Paragraphs)
{
sw.Write(paragraph.Text);
}
}
}
}
}
}

Update a Textbox in a Word Document
To update a text box, first clear its existing content using the TextBox.ChildObjects.Clear() method. Then, add a new paragraph and set its text.
The steps to update a textbox in a Word document are as follows:
- Create a Document object.
- Load a Word file using Document.LoadFromFile() method.
- Get a specific textbox using Document.TextBoxes[index] property
- Remove existing content of the textbox using TextBox.ChildObjects.Clear() method.
- Add a paragraph to the textbox using TextBox.Body.AddParagraph() method.
- Add text to the paragraph using Paragraph.AppendText() method.
- Save the document to a different Word file.
- C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace UpdateTextbox
{
class Program
{
static void Main(string[] args)
{
// Create a Document object
Document document = new Document();
// Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.docx");
// Get a specific textbox
TextBox textBox = document.TextBoxes[0];
// Remove child objects of the textbox
textBox.ChildObjects.Clear();
// Add a new paragraph to the textbox
Paragraph paragraph = textBox.Body.AddParagraph();
// Set line spacing
paragraph.Format.LineSpacing = 15f;
// Add text to the paragraph
TextRange textRange = paragraph.AppendText("The text in this textbox has been updated.");
// Set font size
textRange.CharacterFormat.FontSize = 15f;
// Save the document to a different Word file
document.SaveToFile("UpdateTextbox.docx", FileFormat.Docx2019);
// Dispose resources
document.Dispose();
}
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
C#/VB.NET: Find and Highlight Text in Word
Finding specific text or phrases in a long Word document can be a bit of a hassle. Fortunately, MS Word provides the "Find" function to locate specific content in a document quickly. You can also highlight the found content with a background color to ensure that they won't be overlooked by the readers. This article will demonstrate how to programmatically find and highlight text in a Word document using Spire.Doc for .NET.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLLs files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Find and Highlight Text in a Word Document
The detailed steps are as follows.
- Create a Document instance
- Load a sample Word document using Document.LoadFromFile() method.
- Find all matching text in the document using Document.FindAllString(string matchString, bool caseSensitive, bool wholeWord) method.
- Loop through all matching text in the document.
- Get the text range of a specific matching text using TextSelection.GetAsOneRange() method, and then set its highlight color using TextRange.CharacterFormat.HighlightColor property.
- Save the result file using Document.SaveToFile() method.
- C#
- VB.NET
using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;
namespace FindHighlight
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document document = new Document();
//Load a sample Word document
document.LoadFromFile("input.docx");
//Find all matching text in the document
TextSelection[] text = document.FindAllString("transcendentalism", false, true);
//Loop through all matching text and set highlight color for them
foreach (TextSelection seletion in text)
{
seletion.GetAsOneRange().CharacterFormat.HighlightColor = Color.Yellow;
}
//Save the result file
document.SaveToFile("FindHighlight.docx", FileFormat.Docx);
}
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
C#/VB.NET: Extract Text and Images from Word
When receiving or downloading a Word document from the Internet, you may sometimes need to extract content from the document for other purposes. In this article, you will learn how to programmatically extract text and images from a Word document using Spire.Doc for .NET.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Extract Text from a Word Document
Below are detailed steps on how to extract text from a Word document and save in a TXT file.
- Create a Document instance.
- Load a sample Word document using Document.LoadFromFile() method.
- Create a StringBuilder instance.
- Get each paragraph of each section in the document.
- Get the text of a specified paragraph using Paragraph.Text property, and then append the extracted text to the StringBuilder instance using StringBuilder.AppendLine() method.
- Create a new txt file and write the extracted text to the file using File.WriteAllText() method.
- C#
- VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using System.Text;
using System.IO;
namespace ExtractTextfromWord
{
class ExtractText
{
static void Main(string[] args)
{
//Create a Document instance
Document document = new Document();
//Load a sample Word document
document.LoadFromFile("input.docx");
//Create a StringBuilder instance
StringBuilder sb = new StringBuilder();
//Extract text from Word and save to StringBuilder instance
foreach (Section section in document.Sections)
{
foreach (Paragraph paragraph in section.Paragraphs)
{
sb.AppendLine(paragraph.Text);
}
}
//Create a new txt file to save the extracted text
File.WriteAllText("Extract.txt", sb.ToString());
}
}
}

Extract Images from a Word Document
Below are detailed steps on how to extract all images from a Word document.
- Create a Document instance and load a sample Word document.
- Get each paragraph of each section in the document.
- Get each document object of a specific paragraph.
- Determine whether the document object type is picture. If yes, save the image out of the document using DocPicture.Image.Save(String, ImageFormat) method.
- C#
- VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System;
namespace ExtractImage
{
class Program
{
static void Main(string[] args)
{
//Load a Word document
Document document = new Document("input.docx");
int index = 0;
//Get each section of document
foreach (Section section in document.Sections)
{
//Get each paragraph of section
foreach (Paragraph paragraph in section.Paragraphs)
{
//Get each document object of a specific paragraph
foreach (DocumentObject docObject in paragraph.ChildObjects)
{
//If the DocumentObjectType is picture, save it out of the document
if (docObject.DocumentObjectType == DocumentObjectType.Picture)
{
DocPicture picture = docObject as DocPicture;
picture.Image.Save(string.Format("image_{0}.png", index), System.Drawing.Imaging.ImageFormat.Png);
index++;
}
}
}
}
}
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
C#: Find and Replace Text in Word Documents
When it comes to editing documents, making changes to the text is a common task. Microsoft Word provides a robust feature called "Find and Replace" that streamlines the text editing process. With this feature, you can effortlessly locate specific words, phrases, or characters within your document and replace them in one simple action. This eliminates the need for repetitive manual searching and time-consuming edits, saving you valuable time and effort, especially when you need to make widespread changes in lengthy documents. In this article, we will explain how to find and replace text in Word documents in C# using Spire.Doc for .NET.
- Find Text and Replace All Its Instances with New Text
- Find Text and Replace Its First Instance with New Text
- Find and Replace Text with Image
- Find and Replace Text using Regular Expression
- Find and Replace Text with Content from Another Word Document
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Find Text and Replace All Its Instances with New Text
Spire.Doc for .NET provides the Document.Replace() method that enables you to find and replace specific text in a Word document. With this method, you can seamlessly replace all instances of the target text with new content. Additionally, you have the flexibility to specify whether the search should be case-sensitive and whether whole-word matching should be considered. The detailed steps are as follows.
- Instantiate an object of the Document class.
- Load a sample Word document using Document.LoadFromFile() method.
- Replace all instances of specific text with new text using Document.Replace(string matchString, string newValue, bool caseSensitive, bool wholeWord) method.
- Save the result document using Document.SaveToFile() method.
- C#
using Spire.Doc;
namespace ReplaceAllText
{
internal class Program
{
static void Main(string[] args)
{
//Instantiate an object of the Document class
Document document = new Document();
//Load a sample Word document
document.LoadFromFile("Sample.docx");
//Replace all instances of specific text with new text
document.Replace("Spire.Doc", "Eiceblue", false, true);
//Save the result document
document.SaveToFile("ReplaceAllText.docx", FileFormat.Docx2016);
document.Close();
}
}
}

Find Text and Replace Its First Instance with New Text
To replace the first instance of a specific text in a Word document using Spire.Doc for .NET, you can utilize the Document.ReplaceFirst property. By setting this property to true before calling the Document.Replace() method, you can change the text replacement mode to exclusively replace the first instance. The detailed steps are as follows.
- Instantiate an object of the Document class.
- Load a sample Word document using Document.LoadFromFile() method.
- Change the text replacement mode to replace the first instance only by setting the Document.ReplaceFirst property to true.
- Call the Document.Replace(string matchString, string newValue, bool caseSensitive, bool wholeWord) method to replace text.
- Save the result document using Document.SaveToFile() method.
- C#
using Spire.Doc;
namespace ReplaceFirstText
{
internal class Program
{
static void Main(string[] args)
{
//Instantiate an object of the Document class
Document document = new Document();
//Load a sample Word document
document.LoadFromFile("Sample.docx");
//Change the text replacement mode to replace the first instance only
document.ReplaceFirst = true;
//Replace the first instance of specific text with new text
document.Replace("Spire.Doc", "Eiceblue", false, true);
//Save the result document
document.SaveToFile("ReplaceFirstText.docx", FileFormat.Docx2016);
document.Close();
}
}
}
Find and Replace Text with Image
Sometimes, you may need to replace text with images for visual representation or design purposes. In Spire.Doc for .NET, replacing text with image can be achieved by inserting the image at the position of the target text and then removing the text from the document. The detailed steps are as follows.
- Instantiate an object of the Document class.
- Load a sample Word document using Document.LoadFromFile() method.
- Find specific text in the document using Document.FindAllString() method.
- Loop through the matched text.
- For each matched text, get the paragraph where it is located and get the position of the text in the paragraph.
- Instantiate an object of the DocPicture class, and then load an image using DocPicture.LoadImage() method.
- Insert the image into the paragraph at the position of the text and then remove the text from the paragraph.
- Save the result document using Document.SaveToFile() method.
- C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace ReplaceTextWithImage
{
internal class Program
{
static void Main(string[] args)
{
//Instantiate an object of the Document class
Document document = new Document();
//Load a sample Word document
document.LoadFromFile("Sample.docx");
//Find specific text in the document
TextSelection[] selections = document.FindAllString("Spire.Doc", true, true);
int index = 0;
Paragraph ownerParagraph = null;
//Loop through the matched text
foreach (TextSelection selection in selections)
{
//Get the paragraph where the text is located
ownerParagraph = selection.GetAsOneRange().OwnerParagraph;
//Get the index position of the text in the paragraph
index = ownerParagraph.ChildObjects.IndexOf(selection.GetAsOneRange());
//Load an image
DocPicture pic = new DocPicture(document);
pic.LoadImage("img.png");
//Insert the image into the paragraph at the index position of the text
ownerParagraph.ChildObjects.Insert(index, pic);
//Remove the text from the paragraph
ownerParagraph.ChildObjects.Remove(selection.GetAsOneRange());
}
//Save the result document
document.SaveToFile("ReplaceTextWithImage.docx", FileFormat.Docx2016);
document.Close();
}
}
}

Find and Replace Text using Regular Expression
Regular expressions offer a robust toolset for performing complex search and replace operations within documents. The Document.Replace() method can leverage regular expressions to search for specific text, allowing you to perform advanced search and replace operations based on specific criteria. The detailed steps are as follows.
- Instantiate an object of the Document class.
- Load a sample Word document using Document.LoadFromFile() method.
- Instantiate an object of the Regex class to match text based on specific criteria.
- Replace the matched text with new text using Document.Replace(Regex pattern, string replace) method.
- Save the resulting document using Document.SaveToFile() method.
- C#
using Spire.Doc;
using System.Text.RegularExpressions;
namespace ReplaceTextWithRegex
{
internal class Program
{
static void Main(string[] args)
{
//Instantiate an object of the Document class
Document document = new Document();
//Load a sample Word document
document.LoadFromFile("Sample.docx");
//Create a regex to match the text that starts with #
Regex regex = new Regex(@"\#\w+\b");
//Replace the matched text with new text
document.Replace(regex, "Spire.Doc");
//Save the result document
document.SaveToFile("ReplaceTextWithRegex.docx", FileFormat.Docx2016);
document.Close();
}
}
}
Find and Replace Text with Content from Another Word Document
In addition to replacing text with new text or image, Spire.Doc for .NET also enables you to replace text with content from another Word document. This can be beneficial when you are working on a predefined Word template and need to incorporate contents from other Word documents into it. The detailed steps are as follows.
- Instantiate an object of the Document class.
- Load a sample Word document using Document.LoadFromFile() method.
- Load another Word document into an IDocument object.
- Replace specific text in the sample document with content from another document using Document.Replace(string matchString, IDocument matchDoc, bool caseSensitive, bool wholeWord) method.
- Save the result document using Document.SaveToFile() method.
- C#
using Spire.Doc;
using Spire.Doc.Interface;
namespace ReplaceTextWithDocument
{
internal class Program
{
static void Main(string[] args)
{
//Instantiate an object of the Document class
Document document = new Document();
//Load a sample Word document
document.LoadFromFile("Template.docx");
//Load another Word document
IDocument document1 = new Document("Report.docx");
//Replace specific text in the sample document with content from another document
document.Replace("Annual Sales", document1, false, true);
//Save the result document
document.SaveToFile("ReplaceTextWithDocument.docx", FileFormat.Docx2016);
document.Close();
}
}
}
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.