user770785
user770785

Reputation:

Read word Doc. using c#

I have created an application. The text in the rich textbox is stored in word doc. using word interop dll. Now i want to read the word doc back to my richtextbox.

I used oDoc.Content.Text to read. Its working but the alignment is not there. I need to load with the same alingment in the word doc.

And also i used this code

oDoc.Activate();
oDoc.ActiveWindow.Selection.WholeStory();
oDoc.ActiveWindow.Selection.Copy()
IDataObject data = Clipboard.GetDataObject();
txtdocument.Text = Clipboard.GetDataObject()
       .GetData(DataFormats.Text).ToString();

But it throws this error:

Object reference not set to an instance of an object.

Upvotes: 1

Views: 1086

Answers (2)

Benny Tjia
Benny Tjia

Reputation: 4883

It may be possible that Clipboard.GetDataObject(); returns a null reference and then in the very last line you try to access its member

txtdocument.Text = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString();

Anyway just as a suggestion, why you dont replace the last line

txtdocument.Text = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString();

with this:

txtdocument.Text = data.GetData(DataFormats.Text).ToString();

EDIT: check if either one of your variables oDoc, txtDocument, or data is null..

NEW EDIT :

Thread tempThread = new Thread(new ThreadStart(threadstuff))
tempThread.SetApartmentState(System.Threading.ApartmentState.STA);
tempThread.Start();

Upvotes: 0

Guvante
Guvante

Reputation: 19203

Is your program single threaded apartment? If not the Clipboard class will not work.

Reference

The Clipboard class can only be used in threads set to single thread apartment (STA) mode. To use this class, ensure that your Main method is marked with the STAThreadAttribute attribute.

Upvotes: 2

Related Questions