0

I have some code to print docx document:

Microsoft.Office.Interop.Word.Application wordInstance = new Microsoft.Office.Interop.Word.Application();
FileInfo wordFile = new FileInfo("1.docx");
object fileObject = wordFile.FullName;
object oMissing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word.Document doc = wordInstance.Documents.Open(ref fileObject);
doc.Activate();
doc.PrintOut(oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, 
    oMissing, oMissing, oMissing, oMissing);

But I receive exception on wordInstance.Documents.Open():

unable to cast COM object of type 'microsoft.Office.Interop.Word.ApplicationClass' to 'microsoft.Office.Interop.Word.Application'"

I have Word 2016 and Microsoft.Office.Interop.Word Version 15.0.0.0.

How can I solve the problem?

Anton23
  • 2,079
  • 5
  • 15
  • 28
  • You receive an Excel error about the Word interop? – Equalsk Feb 26 '16 at 14:43
  • Thank you for editing, that was confusing. – Equalsk Feb 26 '16 at 14:47
  • Since VS2010, it is no longer necessary to specify `ref oMissing`. You can just omit such optional parameters https://msdn.microsoft.com/en-us/library/dd264738.aspx –  Feb 26 '16 at 14:48
  • I removed ref oMissing – Anton23 Feb 26 '16 at 14:55
  • Are you sure the `15.0.0.0` version of the Interop works with 2016 Word, could you try with a previous edition of word? – Stephen Ross Feb 26 '16 at 15:07
  • What happens if you change this line `Microsoft.Office.Interop.Word.Application wordInstance = ...` to `dynamic wordInstance = ...`? http://stackoverflow.com/a/2675190/585968 –  Feb 26 '16 at 15:12
  • 1
    There is something you are not telling us. Where you got that 15.0.0.0 version is not something you should avoid mentioning, Microsoft does not publish the PIAs for Office 2013. Don't just blindly download something from the Internet. – Hans Passant Feb 26 '16 at 17:17

1 Answers1

0

I found a solution:

dynamic wordInstance = new Microsoft.Office.Interop.Word.Application();
FileInfo wordFile = new FileInfo("2.docx");
object fileObject = wordFile.FullName;
object oMissing = System.Reflection.Missing.Value;
dynamic doc = wordInstance.Documents.Open(ref fileObject);
doc.Activate();
doc.PrintOut(oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);

I had to use dynamic when creating a WordApplication and opening wordInstance.Documents.Open

Thanks to MickyD for a good idea!

Community
  • 1
  • 1
Anton23
  • 2,079
  • 5
  • 15
  • 28