How to find and replace any text content in the document using C# and .NET

  1. Add SautinSoft.Document from Nuget.
  2. Load a DOCX document.
  3. Use methods Find() and Replace().
  4. Save the document.

Here we'll show you how to using the find and replace methods.

Our task is find the word - "Bean" and change it on - "Joker". We will use regular expressions (Regex).

Test Document

A few steps:

  1. Notice you are importing the SautinSoft.Document namespace.
    using SautinSoft.Document;
  2. First of all, create a DocumentCore object with name dc.
    
    DocumentCore dc = new DocumentCore();
    
    DocumentCore is root class, it represents a document itself.
  3. Using regular expressions, we'll find - "Bean" (bean, BEAN, bEan, etc) and replace to - "Joker".
    
                Regex regex = new Regex(@"bean", RegexOptions.IgnoreCase);
    
                //Find "Bean" and Replace everywhere to "Joker"
                foreach (ContentRange item in dc.Content.Find(regex))
                {
                    item.Replace("Joker");
                }
    
    
  4. Save our document into PDF format.
    
                string savePath = Path.ChangeExtension(loadPath, ".replaced.pdf");
                dc.Save(savePath, new PdfSaveOptions());
                System.Diagnostics.Process.Start(savePath);
    
    Download the result PDF document: Replaced.pdf
 

Complete code

using System.IO;
using SautinSoft.Document;
using System.Linq;
using System.Text.RegularExpressions;

namespace Sample
{
    class Sample
    {

        static void Main(string[] args)
        {
            // Get your free 30-day key here:   
            // https://sautinsoft.com/start-for-free/

            FindAndReplace();
        }

        /// <summary>
        /// Find and replace a text using ContentRange.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/find-replace-content-net-csharp-vb.php
        /// </remarks>
        public static void FindAndReplace()
        {
            // Path to a loadable document.
            string loadPath = @"..\..\..\critique.docx";

            // Load a document intoDocumentCore.
            DocumentCore dc = DocumentCore.Load(loadPath);

            Regex regex = new Regex(@"bean", RegexOptions.IgnoreCase);

            //Find "Bean" and Replace everywhere on "Joker :-)"
            // Please note, Reverse() makes sure that action replace not affects to Find().
            foreach (ContentRange item in dc.Content.Find(regex).Reverse())
            {
                item.Replace("Joker");
            }

            // Save our document into PDF format.
            string savePath = "Replaced.pdf";
            dc.Save(savePath, new PdfSaveOptions());

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(loadPath) { UseShellExecute = true });
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(savePath) { UseShellExecute = true });
        }
    }
}

Download

Imports System.IO
Imports SautinSoft.Document
Imports System.Linq
Imports System.Text.RegularExpressions

Module Sample
    Sub Main()
        FindAndReplace()
    End Sub
    ''' Get your free 30-day key here:   
    ''' https://sautinsoft.com/start-for-free/
    ''' <summary>
    ''' Find and replace a text using ContentRange.
    ''' </summary>
    ''' <remarks>
    ''' Details: https://sautinsoft.com/products/document/help/net/developer-guide/find-replace-content-net-csharp-vb.php
    ''' </remarks>
    Sub FindAndReplace()
        ' Path to a loadable document.
        Dim loadPath As String = "..\..\..\critique.docx"

        ' Load a document intoDocumentCore.
        Dim dc As DocumentCore = DocumentCore.Load(loadPath)

        Dim regex As New Regex("bean", RegexOptions.IgnoreCase)

        'Find "Bean" and Replace everywhere on "Joker :-)"
        ' Please note, Reverse() makes sure that action replace not affects to Find().
        For Each item As ContentRange In dc.Content.Find(regex).Reverse()
            item.Replace("Joker")
        Next item

        ' Save our document into PDF format.
        Dim savePath As String = "Replaced.pdf"
        dc.Save(savePath, New PdfSaveOptions())

        ' Open the result for demonstration purposes.
        System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(loadPath) With {.UseShellExecute = True})
        System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(savePath) With {.UseShellExecute = True})
    End Sub
End Module

Download

If you need a new code example or have a question: email us at support@sautinsoft.com or ask at Online Chat (right-bottom corner of this page).