In this short tutorial, we will understand how to find and replace text in Word document using C#. In C# Word document replace text is possible using simple API calls for any of .NET based applications whether you are using MS Windows, Linux, or macOS operating systems.
Steps to Replace Text in Word document using C#
- Configure Aspose.Words library from NuGet package manager using MS Visual Studio
- Create an instance of the Document class for loading the source Word file
- Instantiate FindReplaceOptions class object to set different properties
- Set the search and replace string in the Replace method along with different properties
- Save the output word file with replaced string values
In above steps, the input Word document is loaded and then you can specify different properties to find and replace the text, including finding whole words, replace direction and match case. Finally, save the output file after completing the process to replace text in Word document using C#.
Code to Find and Replace Text in Word document using C#
using System; | |
using Aspose.Words; | |
using Aspose.Words.Replacing; | |
namespace FindAndReplaceTextInWordDocumentInCsharp | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
// Use Aspose.Words license to remove trial version limitations after replacing text in Word document | |
License licenseForReplacingTextInWord = new License(); | |
licenseForReplacingTextInWord.SetLicense("Aspose.Words.lic"); | |
// Load an input Word file with Document class | |
Document doc = new Document("Input.docx"); | |
// Initialize FindReplaceOptions class object to replace text string | |
FindReplaceOptions options = new FindReplaceOptions(); | |
options.MatchCase = true; | |
options.Direction = FindReplaceDirection.Forward; | |
options.FindWholeWordsOnly = true; | |
// Set the search and replace string in the Replace method | |
doc.Range.Replace("Sample", "Replace", options); | |
// Save the result | |
doc.Save("FindAndReplace.docx"); | |
} | |
} | |
} |
In the above example using C# DOCX replace text is easily possible in few lines of code. The process starts by loading input Word document using an instance of Document class, which is then followed by setting different properties of FindReplaceOptions Class to adjust text replacing process. Finally replace text in Word document using C# is completed by Save method.
In this article, we have learned how using C# replace text in Word document is easily possible. However, if you want to learn sending word document by email, refer to the article on how to Send Word Document by Email using C#.