151-open-word-doc-in-c

Reading Time: 1 minute

To handle MS Office documents from C# it is essential to add assembly to your C# project. Reference for handling MS Office documents is in microsoft.office.interop.word.dll. So you need to download this dll file first. Next step is to add reference, like for any other dll included in your current project. Name space

using Microsoft.Office.Interop.Word;

has to be included as well.
Now, we need three objects to open word doc in C#:

object fileName = openFileDialog1.FileName;
object readOnly = false;
object isVisible = true;

Next step is to open MS Word application from C#.

var applicationWord = new Microsoft.Office.Interop.Word.Application();
applicationWord.Visible = true;

Then, we need one object of Document class.

Document doc = applicationWord.Documents.Open(fileName, ReadOnly: false, Visible: true);

After that, we collect all the words from the document into string.

string str_all = “”;
int count = doc.Words.Count;
for (int i = 1; i <= count; i++)
{

string str_word_to_text = doc.Words[i].Text;
str_all += str_word_to_text;

}

Finally, MS Word can be closed.

applicationWord.Quit();

Whole code is as follows:

if (openFileDialog1.ShowDialog() == DialogResult.OK)
{

object fileName = openFileDialog1.FileName;
object readOnly = false;
object isVisible = true;

var applicationWord = new Microsoft.Office.Interop.Word.Application();
applicationWord.Visible = true;

Document doc = applicationWord.Documents.Open(fileName, ReadOnly: false, Visible: true);

string str_all = “”;
int count = doc.Words.Count;
for (int i = 1; i <= count; i++)
{

string str_word_to_text = doc.Words[i].Text;
str_all += str_word_to_text ;

}

applicationWord.Quit();

}

External links:

Open Word doc in C# in Dotnetperls
Open Word doc in C# in Omegacoder
Open Word doc in C# in Sharpcorner

Leave a Reply

Your email address will not be published. Required fields are marked *

*