Working with word document through c#.net desktop application

This article will help you to open a Word document,read the file contents and also write to it. Just a few steps to follow.

Follow these step:
1) Go to Solution Explorer / Add Reference  to microsoft word 11.0 object library.

To access a Word document we need to do these steps:

  1. Create an instance of Word.ApplicationClass
  2. Use the applicationclass to open a Word.Document
  3. Process the document, either reading from it or writing to it.
  4. Close the Word Document (optionally saving changes)
  5. Quit the applicationclass
  6. Discard the left over COM object. (This is to overcome what I believe is a bug. If you don't do this, you will find lots of WORD.EXE instances in your task manager)

This code will create the word application:

Word.ApplicationClass wordApplication;
try
{
wordApplication = new Word.ApplicationClass();
}
catch (Exception e)
{
MessageBox.Show("ERROR! Do you have MS Word installed? "+ e.Message.ToString());
}
To open the word documnet Follow this:
object o_null = System.Reflection.Missing.Value;

object o_true = ???
object o_false = ???
object o_filePath = @"C:\my\filename.doc";
Word.Document doc;
try
{
   doc = wordApplication.Documents.Open(ref o_filePath,
   ref o_null, ref o_null, ref o_null, ref o_null, ref o_null,
   ref o_null, ref o_null, ref o_null, ref o_null, ref o_null,
   ref o_null, ref o_null, ref o_null, ref o_null, ref o_null);
}
catch (Exception e)
{
MessageBox.Show("ERROR! Couldn't open that file. "+ e.Message.ToString());
}








if you want to read text from the file, you can use
string alltext = doc.Content.Text






To save the document:
object o_filename = @"C:\a\nice\filename.doc";
object o_format = Word.WdSaveFormat.wdFormatHTML;
object o_encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8;
object o_endings = Word.WdLineEndingType.wdCRLF;
try
{
   wordApplication.ActiveDocument.SaveAs(ref o_filename, ref o_format, ref o_null,
   ref o_null, ref o_null, ref o_null, ref o_null, ref o_null, ref o_null,
   ref o_null, ref o_null, ref o_encoding, ref o_null,
   ref o_null, ref o_endings, ref o_null);
}
catch (Exception e)
{
MessageBox.Show("ERROR! Couldn't save that file. "+ e.Message.ToString());
}
You must remember to quit the Word application and to discard the COM object afterwards:

doc.Close(ref o_null, ref o_null, ref o_null);
wordApplication.Quit(ref o_null, ref o_null, ref o_null);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApplication);


hope this help:
Cheers..







By alice johnson   Popularity  (4240 Views)