0
votes

I am trying to paste some text in a word file in c# and I tried this code from a stackoverflow post:

Microsoft.Office.Interop.Word.Application wordApp = null;
wordApp = new Microsoft.Office.Interop.Word.Application();
wordApp.Visible = true;
var filePath = @"H:\5555\Documents\Doc1.doc";
Document wordDoc = wordApp.Documents.Open(filePath);
Bookmark bkm = wordDoc.Bookmarks["name_field"];
Microsoft.Office.Interop.Word.Range rng = bkm.Range;
rng.Text = "Adams Laura"; //Get value from any where

So I get this error: Cannot implicitly convert "string" to "object" when I run this line.

"Document wordDoc = wordApp.Documents.Open(filePath);"

But I have no idea what kind of object I have to use.

1
Try converting it explicitly, e.g. (object)filePathAlex
Here's something that you should find useful. I think @Alex has already answered your question but this could also be useful: stackoverflow.com/questions/2690623/… - look at the answer from Lasse V. Karlsen.sr28
A string is an object so i don't unerstand that errorTim Schmelter
i tried your code and change path of doc, it worksPranav Patel

1 Answers

1
votes

Word's COM world can do things "pure" C# doesn't "like"/understand. One of those things is optional parameters. C# uses the concept "overloading" when a method can accept a different number and/or combination of parameters; the classic VB/COM world has a single method with optional parameters. So the PIAs present these to C# as data type object that need to be passed "by reference". If the parameter is not used, then ref Type.Missing is passed.

Newer versions of C# can accomodate the classic VB/COM idiosyncracies a bit better, but when you run into something you describe try:

object oFilePath = filePath;
Document wordDoc = wordApp.Documents.Open(ref oFilePath);

If you get another error, look at Intellisense for the Open method for the version of Word you're programming against and add ref Type.Missing for the remaining parameters listed in the Intellisense "tip".