Search code examples
c#interopms-wordms-officemailmerge

Opening a Word Document that contains Merge Fields and connects to a datasource from C#


I have a function which opens a document in Word at a specified location:

static void OpenWordDocument(string fileName)
{
Type applicationType = Type.GetTypeFromProgID("Word.Application");
object applicationObject = Activator.CreateInstance(applicationType);

object documentsObject = applicationType.InvokeMember("Documents", System.Reflection.BindingFlags.GetProperty, null, applicationObject, null);
applicationType.InvokeMember("Visible", System.Reflection.BindingFlags.SetProperty, null, applicationObject, new object[] { true });

Type documentsType = documentsObject.GetType();
object documentObject = documentsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, documentsObject, new Object[] { fileName });
}

It works fine with Office 2003, but when opening the document on a system using Office 2010, the document doesn't seem to be able to connect to the datasource. What could be causing this? Am I missing any properties when opening the document that could be blocking the connection?


Solution

  • We solved it with a bit of a workaround~

    Rather than go through the Interop assemblies and create an instance of Word, we just created a process which ran a .bat file which opened the documents :x

    static void OpenWordDocument()
    {
    System.Diagnostics.Process proc = new System.Diagnostics.Process();
    proc.EnableRaisingEvents = false;
    proc.StartInfo.FileName = @"fileName.bat";
    proc.Start();
    }
    

    This isn't an ideal solution, so any other solutions would be great!