Search code examples
c#winformsoffice-interop

Search for a word in whole word document without opening it


I want searching for a word in whole word document without opening it.

I search in every site and read all Questions here but there is an error when using this code (Using a Range Object)

object findText = "find me";

Word.Range rng = this.Paragraphs[2].Range; 

rng.Find.ClearFormatting();

if (rng.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("Text not found.");
} 

rng.Select(); 

But I have an error in

Paragraphs[2]

when open big file. The error is:

ref missing


Solution

  • You should count the paragraphs numbers in whole document using

    int docc = wordfile.Paragraphs.Count;
    

    So when you open big files, it will count all paragraphs in the file. Then using (( docc )) in the range code

    Range rng = wordfile.Paragraphs[docc].Range;
    

    Second error you can use (( Type.Missing )) instead of (( ref missing ))

    so the code will be

    object findText = "find me";
    int docc = wordfile.Paragraphs.Count;
    Range rng = wordfile.Paragraphs[docc].Range;
    rng.Find.ClearFormatting();
    
    if (rng.Find.Execute(ref findText,
    Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,Type.Missing,
    Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
    Type.Missing, Type.Missing)) 
     { 
      MessageBox.Show("Text found.");
     } 
    else 
    { 
     MessageBox.Show("Text not found.");
    } 
    
    rng.Select();