Search code examples
c#.netoffice-interop

Can't call Close on Word document without getting a warning


I can't call Close my opened word document:

docs.Close(WdSaveOptions.wdDoNotSaveChanges, nullobject, nullobject);

or Quit on the application:

wordObject.Quit(WdSaveOptions.wdDoNotSaveChanges);

Without getting this compiler warning:

Warning 1 Ambiguity between method 'Microsoft.Office.Interop.Word._Application.Quit(ref object, ref object, ref object)' and non-method 'Microsoft.Office.Interop.Word.ApplicationEvents4_Event.Quit'. Using method group.

And full code:

Microsoft.Office.Interop.Word.Application wordObject = new Microsoft.Office.Interop.Word.Application();
                object file = pathToFile; //this is the path
                object nullobject = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word.Document docs = wordObject.Documents.Open(file, nullobject, nullobject, nullobject,
                nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject);

Using Office library 15.


Solution

  • It's just a warning and you can ignore it. The problem is in the definition of the actual Application interface and it's underlying interfaces in .NET. You can circumvent this warning by casting it to one of the two types proposed in the warning:

    ((Microsoft.Office.Interop.Word._Application)wordObject).Quit(WdSaveOptions.wdDoNotSaveChanges);
    

    This will disambiguate the method call. If you don't do this, there is no harm done.