Monday, 13 October 2014 07:20

Count the number of words in a document in C#, VB.NET

Written by  support iceblue
Rate this item
(0 votes)

When you type in a document, Word automatically counts the number of pages and words in your document and displays them on the status bar – Word Count, at the bottom of the workspace. But how can we get the number of words, characters in an existing Word document through programming? This article aims to give you a simple solution offered by Spire.Doc.

Test file:

Count the number of words in a document in C#, VB.NET

Detailed Steps for Getting the Number of Words and Characters

Step 1: Create a new instance of Spire.Doc.Document class and load the test file.

Document doc = new Document();
doc.LoadFromFile("test.docx", FileFormat.Docx2010);

Step 2: Display the number of words, characters including or excluding spaces on console.

Console.WriteLine("CharCount: " + doc.BuiltinDocumentProperties.CharCount);
Console.WriteLine("CharCountWithSpace: " + doc.BuiltinDocumentProperties.CharCountWithSpace);
Console.WriteLine("WordCount: " + doc.BuiltinDocumentProperties.WordCount);

Output:

Count the number of words in a document in C#, VB.NET

Full Code:

[C#]
Document doc = new Document();
doc.LoadFromFile("test.docx", FileFormat.Docx2010);
Console.WriteLine("CharCount: " + doc.BuiltinDocumentProperties.CharCount);
Console.WriteLine("CharCountWithSpace: " + doc.BuiltinDocumentProperties.CharCountWithSpace);
Console.WriteLine("WordCount: " + doc.BuiltinDocumentProperties.WordCount);
Console.ReadKey();
[VB.NET]
Dim doc As New Document()
doc.LoadFromFile("test.docx", FileFormat.Docx2010)
Console.WriteLine("CharCount: " + doc.BuiltinDocumentProperties.CharCount)
Console.WriteLine("CharCountWithSpace: " + doc.BuiltinDocumentProperties.CharCountWithSpace)
Console.WriteLine("WordCount: " + doc.BuiltinDocumentProperties.WordCount)
Console.ReadKey()

Additional Info

  • tutorial_title: Count the number of words
Last modified on Monday, 13 October 2014 07:26