Error instantiating new Microsoft.Office.Interop.Word.Application object (0x80004002)

0

I am working on a simple C# asp.net Web API that is going to be used to generate Word documents. I am making use of the Microsoft.Office.Interop.Word Nuget package (v 15.0.4797.1003) in this API. I have a very basic method, shown below, which is simply attempting to open an existing word document. Everything is working properly until the code attempts to create a new Application. When that line is hit an exception is thrown. The message says:

Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Word.Application'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{00020970-0000-0000-C000-000000000046}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).

I did some searching around online and most threads were recommending adding [STAThread] to the start of the Main Method. The only issue with that is I'm working on a Web API and don't have a Main Method. I tried adding this to the front of the GenerateDocument method but it didn't resolve the issue. Should I put that [STAThread] line somewhere else or is there some other way to resolve this?

Adding a bit more details: I'm working on a Windows 10 machine with Office 2016 Professional Plus installed.

public class Helpers
{
    [STAThread]
    public void GenerateDocument(string filePath)
    {
        try
        {
            //Parameter check
            if (string.IsNullOrWhiteSpace(filePath))
                return;

            //Creates a new application
            Application app = new Application();

            //Opens the temp document in a new document object
            Document doc = app.Documents.Open(filePath);

            //Closes the document
            doc.Close();
        }
        catch(Exception ex)
        {
            throw ex;
        }
    }
}
c#
asp.net-web-api
office-interop
asked on Stack Overflow Sep 23, 2020 by n00b dba

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0