Friday, September 18, 2009

Reading a word file Using c#

Reading a word file in c# is very simple we just need to add the reference of the COM component in our application. Click on Add >> Reference and Select the COM tab, under that tab please select the Microsoft object library 9.0 or higher. and after this use the following code to read any file...


Microsoft.Office.Interop.Word.ApplicationClass wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
object file = "D:\\Anil\\test\\testfile.doc"; // path for word file
object nullobj = System.Reflection.Missing.Value;
Microsoft.
Office.Interop.Word.Document doc = wordApp.Documents.Open(ref file, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj,ref nullobj, ref nullobj, ref nullobj, ref nullobj);
doc.
ActiveWindow.Selection.WholeStory();
doc.
ActiveWindow.Selection.Copy();
IDataObject data
= Clipboard.GetDataObject();
string allText = data.GetData(DataFormats.Text).ToString();
doc.
Close(ref nullobj, ref nullobj, ref nullobj);
wordApp.
Quit(ref nullobj, ref nullobj, ref nullobj);
Textbox1.
Text = allText);


Happy Coading!!!

Thanks
Anil Kumar Pandey
System Architect
Mumbai, Maharshtra

Kontera