0

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.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Gewoo
  • 437
  • 6
  • 19
  • 1
    Try converting it explicitly, e.g. (object)filePath – Alex Jun 03 '16 at 09:13
  • Here's something that you should find useful. I think @Alex has already answered your question but this could also be useful: http://stackoverflow.com/questions/2690623/what-is-the-dynamic-type-in-c-sharp-4-0-used-for/2690837#2690837 - look at the answer from Lasse V. Karlsen. – sr28 Jun 03 '16 at 09:25
  • A string is an object so i don't unerstand that error – Tim Schmelter Jun 03 '16 at 09:34
  • i tried your code and change path of doc, it works – Pranav Patel Jun 03 '16 at 09:46

1 Answers1

1

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".

Cindy Meister
  • 25,071
  • 21
  • 34
  • 43