1

I try to add a document from template with Microsoft.Office.Interop.Word, using:

Microsoft.Office.Interop.Word.Aplication wordApp = 
             new Microsoft.Office.Interop.Word.Application();

wordApp.Documents.Add("somedoc.dotx");

But I always get an unhandled COMException, telling me the file might be damaged. I tried doc, docx and dotx and I am sure the file exists, because I check it before. When I open the file in Word, it opens fine.

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
  • First argument is the *template*. "somedoc.docx" does not sound much like a template although we never seem to be able to rely on valid code snippets at SO. Oh joy. Consider passing no arguments at all, you don't name the file until you save it. – Hans Passant Dec 14 '16 at 17:28
  • @HansPassant I tried actual templates as well (as it stated in my question). And I do need to use the file as template, I clarified my question a little. – Bart Friederichs Dec 15 '16 at 08:35
  • A related question is [How to create word docs programmatically from a template](http://stackoverflow.com/q/4304238/4519059) ;). – shA.t Dec 15 '16 at 08:51

2 Answers2

2

Turns out, Add() wants a full path:

wordApp.Documents.Add(Path.GetFullPath("somedoc.docx"));

works fine, with both docx and dotx files.

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
0

Use .Add() to add a new file, and .Open() to open an existing file.

https://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.documents.aspx

maniak1982
  • 707
  • 2
  • 7
  • 23
  • I want to create a new file, based on an existing one. `docx` is used as a template here. Basically the only difference between `docx` and `dotx` is Word's behaviour when opening it. For interop this doesn't seem to make a difference. – Bart Friederichs Dec 14 '16 at 16:02
  • I haven't worked with these for a while, but if I recall correctly the documents themselves aren't any different either, from a file structure standpoint. I suspect that you won't have success with trying to use the `.Add()` method on an existing document either way. – maniak1982 Dec 14 '16 at 22:14