Skip to main content

Command Palette

Search for a command to run...

How to Extract Text from Word Document Using C#

Published
4 min readView as Markdown

In daily .NET development, Word document processing is a high-frequency task - whether you’re pulling key clauses from contracts, parsing actionable data from business reports, or extracting fixed fields from template documents. Yet manual copy-pasting remains a stubborn pain point: it’s time-intensive, and even small omissions or typos can lead to costly data inaccuracies that derail downstream workflows.

This guide cuts through the inefficiency by showing you how to implement automated Word content extraction using Free Spire.Doc for .NET. No Microsoft Office installation required, zero cost. We’ll cover everything from basic full-document text extraction to advanced parsing of specific paragraphs and their formatting.


1. What Is Free Spire.Doc for .NET?

Free Spire.Doc for .NET is a lightweight, free Word processing library built explicitly for .NET developers. Its core value lies in solving common pain points of Word automation, with these key advantages:

  • Zero Dependencies: Parse .doc and .docx files directly—no need to install Microsoft Office on your development or production machines.
  • Broad Format Support: Works seamlessly with legacy .doc (97-2003) and modern .docx (2007+) files.
  • Lightweight & Fast: Small library size, rapid file loading, and no extra runtime environment required—ideal for resource-constrained projects.

⚠️ Critical Limitation: Designed for small to medium documents only (supports up to 500 paragraphs).


2. Step-by-Step: Extract Word Content

Step 1. Install Free Spire.Doc via NuGet

Open the console in Visual Studio and run this command (press Enter to execute):

Install-Package FreeSpire.Doc

💡 Pro Tip: After installation, add these namespaces at the top of your C# file:

  • using Spire.Doc; (core functionality for Word files)
  • using Spire.Doc.Documents; (required for formatting tasks, e.g., alignment, spacing)
  • using System.IO; and using System.Text; (for file I/O and text encoding).

Step 2. Basic Use Case: Extract Full Document Text

If you only need to pull all text (ignoring images, tables, or formatting), the GetText() method simplifies this to just a few lines of code:

using Spire.Doc;
using System.IO;

namespace WordContentExtractor
{
    class Program
    {
        static void Main(string[] args)
        {
            // Load your Word file
            Document doc = new Document();
            // Use an absolute path for testing (avoids "file not found" errors)
            doc.LoadFromFile(@"C:\Documents\ContractTemplate.docx");

            // Extract all text
            string fullDocumentText = doc.GetText();

            // Save extracted text to a TXT file 
            string outputPath = @"C:\Documents\Extracted_Contract_Text.txt";
            File.WriteAllText(outputPath, fullDocumentText);

            // Optional: Confirm success to the user
            Console.WriteLine($"Text extracted successfully! Check: {outputPath}");
        }
    }
}

⚠️ Troubleshooting Tip: If you see a “file not found” error:

  • Use an absolute file path (e.g., C:\Docs\File.docx) instead of a relative path (relative paths point to your project’s output folder, e.g., bin/Debug/net6.0).
  • Verify the Word file isn’t open in another program (this locks the file and prevents access).

Step 3. Advanced Use Case: Extract Specific Paragraphs + Formatting

For precision tasks like pulling a contract’s “Payment Terms” section and checking if it’s formatted as a centered title, use Sections (to navigate document sections) and Paragraphs (to target specific text blocks).

Key Note: Paragraph and section indexes start at 0 (not 1), so the 5th paragraph in the 1st section is Paragraphs[4].

using Spire.Doc;
using Spire.Doc.Documents;
using System.IO;
using System.Text;

namespace AdvancedWordExtractor
{
    class Program
    {
        static void Main(string[] args)
        {
            // 1Load the Word document
            Document doc = new Document();
            doc.LoadFromFile(@"C:\Documents\ContractTemplate.docx");

            // Get the 5th paragraph (index 4) in the 1st section (index 0)
            Section targetSection = doc.Sections[0];
            Paragraph targetParagraph = targetSection.Paragraphs[4];

            // Extract paragraph content + formatting details
            string paraText = targetParagraph.Text; // The actual text of the paragraph
            HorizontalAlignment textAlignment = targetParagraph.Format.HorizontalAlignment; // Left/Center/Right
            float beforeSpacing = targetParagraph.Format.BeforeSpacing; // Spacing before the paragraph (in points)
            float afterSpacing = targetParagraph.Format.AfterSpacing; // Spacing after the paragraph (in points)

            // 4. Save results (include formatting data for audit or reporting)
            string outputPath = @"C:\Documents\Target_Paragraph_Details.txt";
            using (StreamWriter writer = new StreamWriter(outputPath, false, Encoding.UTF8))
            {
                writer.WriteLine("=== Target Paragraph Details ===");
                writer.WriteLine($"Paragraph Text: {paraText}");
                writer.WriteLine($"Text Alignment: {textAlignment}");
                writer.WriteLine($"Spacing Before: {beforeSpacing}pt | Spacing After: {afterSpacing}pt");
            }

            Console.WriteLine($"Paragraph details saved to: {outputPath}");
        }
    }
}

4. Ideal Use Cases for Free Spire.Doc for .NET

This library shines for scenarios where simplicity and cost-efficiency matter most:

  • Individual developers or small teams: No budget for expensive Office automation tools? This is a free alternative.
  • Small-document tasks: Contracts, single-page reports, or template-based files (≤500 paragraphs).
  • Basic to moderate extraction needs: Pulling text, formatting, tables, or images (it supports table cell extraction and image saving too).

Final Takeaway

Free Spire.Doc for .NET is a practical, no-fuss solution for lightweight Word automation. It eliminates the inefficiency of manual copy-pasting and the complexity of Office-dependent tools—all while being free and easy to integrate into your .NET projects. Whether you’re building a contract parser or a report data extractor, this library gets the job done without unnecessary bloat.

More from this blog

coding

19 posts