Read a word .docx file without using interop with c shar c#

Read a word .docx file without using interop with c shar c#

you can install this package using nuget.

using DocumentFormat.OpenXml.Packaging;

get the word docx file path and get page text with this code and copy text to a richtextbox control

var filePath = txtWordFilePath.Text;

const string wordmlNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";

StringBuilder textBuilder = new StringBuilder();
// using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(file.OpenBinaryStream(), false))
using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(filePath, false))
{
    // Manage namespaces to perform XPath queries.  
    NameTable nt = new NameTable();
    XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
    nsManager.AddNamespace("w", wordmlNamespace);

    // Get the document part from the package.  
    // Load the XML in the document part into an XmlDocument instance.  
    XmlDocument xdoc = new XmlDocument(nt);
    xdoc.Load(wdDoc.MainDocumentPart.GetStream());

    XmlNodeList paragraphNodes = xdoc.SelectNodes("//w:p", nsManager);
    foreach (XmlNode paragraphNode in paragraphNodes)
    {
        XmlNodeList textNodes = paragraphNode.SelectNodes(".//w:t", nsManager);
        foreach (System.Xml.XmlNode textNode in textNodes)
        {
            textBuilder.Append(textNode.InnerText);
        }
        textBuilder.Append(Environment.NewLine);
    }

}
var text = textBuilder.ToString();
rtbPageText.Text = text;

Leave a Comment

Scroll to Top