Search code examples
c#.netms-wordtext-search

Programmatically searching for a text phrase in a Word document using C# but without Word Interop


I am looking for a method via C# to programmatically search for Word documents in a given folder that contain a specific text phrase. The program needs to be able to work without using Word Interop as it may be running on a server.

I have tried to search for solutions, but anything I find is very old and based on outdated versions of libraries and applications.


Solution

  • DocumentFormat.OpenXml is probably your best bet.

    using DocumentFormat.OpenXml.Packaging;
    
    var doc = WordprocessingDocument.Open(filePath, false);
    string content = doc.MainDocumentPart.Document.Body.InnerText;
    
    if (content.Contains("phraseToSearch"))
    {
        //do your thing
    }   
    
    doc.Close();