GetActiveObject() doesn't work when publish to IIS Server

0

I attempt to close the Microsoft Word running via RemoteApp(Inactive window) by .Net Core API. So I used P/Invoke in this but it got me the error. The code works fine in my local computer but failed after published and uploaded to IIS Server.

System.Runtime.InteropServices.COMException (0x800401E3): Operation unavailable (Exception from HRESULT: 0x800401E3 (MK_E_UNAVAILABLE))\r\n at API.Controllers.ExamController.GetActiveObject(Guid& rclsid, IntPtr pvReserved, Object& ppunk)\r\n at API.Controllers.ExamController.GetActiveObject(String progID) in C:\{+FILEPATH++}\Controllers\ExamController.cs:line 83

The weird thing is that the filepath of the error is the path of my local computer not the server.

 [DllImport("oleaut32.dll", PreserveSig = false)]
    static extern void GetActiveObject(ref Guid rclsid, IntPtr pvReserved,

[MarshalAs(UnmanagedType.IUnknown)] out object ppunk);

    [DllImport("ole32.dll")]
    static extern int CLSIDFromProgID(
        [MarshalAs(UnmanagedType.LPWStr)] string lpszProgID, out Guid pclsid);

    [DllImport("ole32.dll")]
    private static extern void CLSIDFromProgIDEx([MarshalAs(UnmanagedType.LPWStr)] String progId, out Guid clsid);

    public static object GetActiveObject(string progID)
    {
        object obj = null;
        Guid clsid;

        try
        {
            CLSIDFromProgIDEx(progID, out clsid);
        }
        catch (Exception)
        {
            CLSIDFromProgID(progID, out clsid);
        }

        GetActiveObject(ref clsid, IntPtr.Zero, out obj);
        return obj;
    }
    [HttpGet(), ActionName("CloseAllMSWord")]
    public IActionResult CloseAllMSWord()
    {
        HttpStatusCode statusCode = HttpStatusCode.OK;
        Microsoft.Office.Interop.Word.Application WordObj = null;
        string result = null;
        string error = null;
        try
        {
            Type acType = Type.GetTypeFromProgID("Word.Application");
            WordObj = (Microsoft.Office.Interop.Word.Application)Activator.CreateInstance(acType, true);
            WordObj = (Microsoft.Office.Interop.Word.Application)GetActiveObject("Word.Application");

            for (int i = 0; i < WordObj.Windows.Count; i++)
            {
                object a = i + 1;
                Microsoft.Office.Interop.Word.Window objWin = WordObj.Windows.get_Item(ref a);
                result += i + ": " + objWin.Caption;
                objWin.Close();
            }
        }
        catch (Exception ex)
        {
            statusCode = HttpStatusCode.InternalServerError;
            error = ex.ToString();
        }
        return CreateResponse(statusCode, result, error);
    }
c#
.net-core
ms-word
pinvoke
office-interop
asked on Stack Overflow Feb 25, 2020 by soulofnature

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0