DEV Community

Cover image for How to Open A Word Document in C#
Mehr Muhammad Hamza
Mehr Muhammad Hamza

Posted on

How to Open A Word Document in C#

Working with Word documents in C# can be challenging, as you need to use Microsoft.Office.Interop.Word namespace, which is complex and low-level. Fortunately, some libraries simplify this task and provide a higher-level and more user-friendly interface for manipulating Word and DOCX documents. In this article, we will introduce one of these libraries, called IronWord, and show you how to use it to open and modify a Word document in C#.

How to Open Microsoft Word Document in C#.?

  1. Install Iron Word Library
  2. Load Word Document in Memory Stream
  3. Read the Content of the Document
  4. Edit the Content of the Document

Iron Word:

IronWord is a library that simplifies working with Word documents in C#. It is based on the Microsoft.Office.Interop.Word namespace, but provides a higher-level and more user-friendly interface for manipulating document elements, such as [text runs], images, tables, and styles. IronWord allows you to create, read, and edit Word and DOCX documents in your applications, without having to deal with the complex and low-level interop classes and methods.

Features of Iron Word:

Some of the features and benefits of IronWord are:

  1. It supports both .NET Framework and .NET Core and can be installed as a NuGet package.
  2. It has a fluent and intuitive syntax that makes it easy to create and modify document elements using method chaining and lambda expressions.
  3. It has a rich set of methods and properties that let you access and manipulate various aspects of the document, such as fonts, colors, alignments, margins, headers, footers, bookmarks, hyperlinks, comments, and more.
  4. It can handle various types of document elements, such as paragraphs, runs, images, tables, lists, shapes, fields, and charts.
  5. It can load and save the document from various sources, such as files, streams, byte arrays, and base64 strings.
  6. It can work with multiple documents at the same time, and can also create and use templates.

Now, Let's set up our project to start working with Word Documents in C#. The very first step is to install Iron Word Library in our project.

Install Iron Word Library:

To install Iron Word Nuget Package using the Package Manager Console, you need to follow these steps:

  1. Navigate to your project or solution in Visual Studio, and then go to the "Tools" menu. From there, select "NuGet Package Manager" and choose "Package Manager Console" to open the Package Manager Console window.
  2. In the console, enter the following command to install IronWord as a NuGet package:

Install-Package IronWord

Wait for the installation to complete, and check the output window for any errors or warnings. Add the following Namespace at the top of your class.

using IronWord;

You can now use IronWord to open and edit Word documents in your C# code.

Code for Opening Word Document in C#:

The following code will load the document from the disk to the memory stream and then read the content of the loaded document. We are using the following document as input.
MS Word Document
The following sample code will read the Microsoft Word document and print all the paragraphs on the console.

static void Main(string[] args)
{
    WordDocument doc = new WordDocument("myTestDocument.docx");
    foreach (Paragraph paragraph in doc.Paragraphs) // Loop Through all Paragrah
    {
        foreach (TextRun textRun in paragraph.TextRuns) // Loop through each line of Paragraph
        {
            Console.Write(textRun.Text); // Print each line on console
        }
        Console.WriteLine(); // Add Line after each Paragraph.
    }
}
Enter fullscreen mode Exit fullscreen mode

It declares a variable named doc and assigns it a new instance of the WordDocument class, passing the name of the Word file (“myTestDocument.docx”) as a parameter. This opens the Word file and loads its contents into memory.

It uses a foreach loop to iterate over the Paragraphs collection of the doc object, which contains all the paragraphs in the Word document. For each paragraph, it is assigned to a variable named paragraph.

It uses another for-each loop to iterate over the TextRuns collection of the paragraph object, which contains all the text runs in the paragraph. A text run is a segment of text with the same formatting. For each text run, it assigns it to a variable named textRun.

In this way, Opening a Word document in C# becomes much easier with Iron Word.
Open Word Document in C#

Edit Text of the Word Document:

Now, as we have learned to load and read the content of the document. Let's learn to edit the content of the same document. The following sample code will load the file, and edit the content of the first paragraph.

static void Main(string[] args)
{
    WordDocument doc = new WordDocument("myTestDocument.docx"); 
    // Edit existing text
    doc.Paragraphs[0].TextRuns[0].Text = "This text is edited Using Iron word Library";
    // Export docx
    doc.SaveAs("myUpdatedDocument.docx");
}
Enter fullscreen mode Exit fullscreen mode

The above code loads the MS Word document in the memory stream. It edits the content of the first paragraph. The updated document is then saved to the device. In this way, we can update the content of the document in C# with simplicity. The Updated document is opened in the MS Word Application as:
Update Word Document in C#

Conclusion:

In conclusion, the process of opening and manipulating Word documents in C# is made more accessible and intuitive with the IronWord library. By abstracting the complexities of Microsoft.Office.Interop.Word namespace, IronWord provides a higher-level interface for working with Word and DOCX files. With features such as support for both .NET Framework and .NET Core, a fluent syntax, and extensive methods for manipulating document elements, IronWord simplifies document processing tasks. By following the outlined steps, developers can effortlessly integrate IronWord, allowing them to load, read, and edit Word documents in a more user-friendly manner. The library's capabilities make it a valuable tool for C# applications, offering a streamlined approach to handling Word documents with efficiency and ease.

Iron Word provides a free trial version. The trial version allows you to use IronWord without any payment, and it includes all the features and methods that IronWord offers. You can also access the documentation and code examples to help you get started with IronWord. If you are satisfied with the free trial of IronWord, you can buy a paid license to continue using it. The paid license will also give you access to one year of support and updates from the IronWord team. You can choose from different license options depending on your needs and budget.

Top comments (0)