Home > OS >  .net word interop: word.Documents.Open returns null
.net word interop: word.Documents.Open returns null

Time:03-29

I'm using .net .4.6.1 and trying to do a mail merge. When i run the following code, which has a valid path to a word (.doc) document, it returns null.

C#

object fileName = pathToDocument;

doc = word.Documents.Open(ref fileName,
    ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing);

Any advice appreciated.

Thanks,

Chris

CodePudding user response:

The signature of the Open method is really confusing but it can be treated with more of a common sense approach, try something like this adjusting the file path of your document ...

static void Main(string[] args)
{
    var fileName = "c:\\temp\\Test.docx";

    var wdApplication = new Microsoft.Office.Interop.Word.Application();
    var wdDocument = wdApplication.Documents.Open(fileName);

    Console.WriteLine(wdDocument.Words.Count);

    wdDocument.Close();
    wdApplication.Quit();
}

CodePudding user response:

The Documents.Open method doesn't require the ref keyword for passing parameters:

doc = word.Documents.Open(pathToDocument,
    ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing);
  • Related