Searching in Word document in C#

We can search some specified text in Microsoft Office Word documents with the help of Find() method, The following example shows how we can search text in document in C# language. This article is copy of the its original post in the C#
For it first we need to add reference of Microsoft.Office.Interop.Word library.
We use late binding concept for initializing object of the word application after that we open word document from the specified file path and then we need to clear formatting from previous searches by using the ClearFormatting method prior to the search.

private void FindText()
        {
            Word.Application objWordApp=new Word.Application();
 
            objWordApp.Visible = false;
            object missing = System.Reflection.Missing.Value;
 
            object filename = "C:\\dfd.doc";
            Microsoft.Office.Interop.Word.Document objDoc;
            objDoc = objWordApp.Documents.Open(ref filename, ref missing, ref missing, ref missing,
         ref missing, ref missing, ref missing, ref missing,
         ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                            ref missing, ref missing);
            object findText = "template";
 
            objDoc.Content.Find.ClearFormatting();
            try
            {
                if (objDoc.Content.Find.Execute(ref findText,
                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing))
                {
                    MessageBox.Show("Text found.");
                }
                else
                {
                    MessageBox.Show("The text could not be found.");
                }
                objDoc.Close(ref missing, ref missing, ref missing);
                objWordApp.Application.Quit(ref missing, ref missing, ref missing);
            }
            catch (Exception ex)
            {
                objDoc.Close(ref missing, ref missing, ref missing);
                objWordApp.Application.Quit(ref missing, ref missing, ref missing);
            }
        }

From above we are finding ‘template’ text in the document, code display ‘Text found’ message if we found text otherwise it will display ‘The text could not be found’.