Find and replace function in Word gains great popularity when people want to replace a certain word or phrase in a long document. If there is no word find and replace function, it may cost hours for people to find and replace word content without making mistakes. But time will be limited to minutes if you find and replace words or phrases by using C#, VB.NET. Now let us look at how to find and replace word content with C#, VB.NET.
How to find and replace word text information with C#, VB.NET
Before I start, I have to introduce my best hand Spire.Doc, which is a professional MS Word component, to help me finish this task. It supports C#, VB.NET, ASP.NET, ASP.NET MVC and Silverlight. You can have a free trial of Spire.Doc and no time limit. Using Spire.Doc, I need three steps to realize the whole task.
How to find and replace word text information with C#, VB.NET
Before I start, I have to introduce my best hand Spire.Doc, which is a professional MS Word component, to help me finish this task. It supports C#, VB.NET, ASP.NET, ASP.NET MVC and Silverlight. You can have a free trial of Spire.Doc and no time limit. Using Spire.Doc, I need three steps to realize the whole task.
Step1: Create a new project
1. Create a new project in Visual Studio.
2. Set the Target Framework in Properties to be .NET Framework 2 or above.
3. Add Spire.Doc Dll as reference.
Step2. Find and Replace word content with C#, VB.NET
1. Load a word document from system.
C# Code:
//Create word document
Document document = new Document();
//Load a file
document.LoadFromFile(@"D:\michelle\JaneEyre.doc");
VB.NET Code:
'Create word document
Dim document As New Document()
'Load file
document.LoadFromFile(@"D:\michelle\JaneEyre.doc")
2. Find and replace word text
C# Code:
//Replace text
document.Replace("Jane Eyre", "Jane Eyre Novel", true, true);
document.Replace("character", "characteristic", true, true);
VB.NET Code:
'Replace text
document.Replace("Jane Eyre", "Jane Eyre Novel", true, true)
document.Replace("character", "characteristic", true, true)
Step3. Save and launch the file.
C# Code:
//Save doc file.
document.SaveToFile("Sample.doc", FileFormat.Doc);
//Launching the MS Word file.
System.Diagnostics.Process.Start("Sample.doc");
VB.NET Code:
'Save doc file.
document.SaveToFile("Sample.doc", FileFormat.Doc)
'Launch the file.
System.Diagnostics.Process.Start("Sample.doc")
Preview
From the two pictures above, you obviously find that ”Jane Eyre” has been replaced by “ Jane Eyre Novel” and “character” has been replaced by “ characteristic”. The whole procedure can be very easy. Use the document.Replace("the word you want to replace", "the final word you want", true, true) method, you can replace any word or phrase in the text according to your need.
More Word Functions