Interoperabilidad de Office no funciona en el servicio de Windows

Tengo un problema muy extraño con Microsoft Office.

Tengo una biblioteca común cuyo único propósito es abrir cualquier tipo de archivo de documento de Word que se le pase (por una ruta de archivo completa ...) y guardar ese documento de Word abierto como un archivo pdf.

El problema extraño es que si consumo esa biblioteca de un servicio de Windows, cada vez que intenta abrir el documento de Word, obtengo un valor nulo ... es decir, el documento de Word nunca se abrió.

Sin embargo, si consumo la biblioteca desde una aplicación WPF o Windows Form, nunca tengo ningún problema. Soy consciente de que hay problemas con el subprocesamiento, (Single Thread Appartment) sin embargo, no tengo idea de cómo solucionarlo para que funcione fuera del servicio de Windows. :( :( :(

¡Apreciaría cualquier ayuda! El error que recibo es el siguiente:

Mensaje de excepción: {"Referencia de objeto no configurada para una instancia de un objeto".} (Refiriéndose a la palabra documento). Excepción interna: nula; HResult: -2147467261. Datos: ListDictionaryInternal con 0 entradas; Seguimiento de la pila: en DocumentConverter.ToPdf (String currentWorkingFolderPath, String pathToDocumentToConvert) en c: \ Project Files ... \ DocumentConverter.cs: line 209

Así que aquí está la función de biblioteca. Requiere la referencia de Microsoft Office, que es creada por Visual Studio Tools para Office.

private string ToPDF(string currentWorkingFolderPath, string pathToDocumentToConvert)
{
    string temporaryPdfFolderPath = Path.GetFullPath(currentWorkingFolderPath + "\\pdf\\");
    string temporaryPdfFilePath = Path.GetFullPath(temporaryPdfFolderPath + "\\pdffile.pdf");

    if (!FileSystem.CreateDirectory(temporaryPdfFolderPath))
    {
        return null;
    }

    try
    {
        Microsoft.Office.Interop.Word.Application wordApplication = new Microsoft.Office.Interop.Word.Application();

        object objectMissing = System.Reflection.Missing.Value;

        wordApplication.Visible = false;
        wordApplication.ScreenUpdating = false;

        FileInfo wordFile = new FileInfo(pathToDocumentToConvert);

        Object fileName = (Object)wordFile.FullName;

        // This is where it breaks when called from windows service. Use the dummy value as a placeholder for optional arguments
        Document wordDocument = wordApplication.Documents.Open(ref fileName, ref objectMissing,            
            true, ref objectMissing, ref objectMissing, ref objectMissing, ref objectMissing,            
            ref objectMissing, ref objectMissing, ref objectMissing, ref objectMissing, ref objectMissing,            
            ref objectMissing, ref objectMissing, ref objectMissing, ref objectMissing);



        object outputFileName = (object)temporaryPdfFilePath;
        object fileFormat = WdSaveFormat.wdFormatPDF ;

        // Save document into PDF Format
        wordDocument.SaveAs(ref outputFileName,
            ref fileFormat, ref objectMissing, ref objectMissing,
            ref objectMissing, ref objectMissing, ref objectMissing, ref objectMissing,
            ref objectMissing, ref objectMissing, ref objectMissing, ref objectMissing,
            ref objectMissing, ref objectMissing, ref objectMissing, ref objectMissing);

        // Close the Word document, but leave the Word application open.
        // doc has to be cast to type _Document so that it will find the
        // correct Close method.                
        object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
        ((_Document)wordDocument).Close(ref saveChanges, ref objectMissing, ref objectMissing);

        wordDocument = null;

        // word has to be cast to type _Application so that it will find
        // the correct Quit method.
        ((Microsoft.Office.Interop.Word._Application)wordApplication).Quit(ref objectMissing, ref objectMissing, ref objectMissing);

        wordApplication = null;

    }
    catch (Exception ex)
    {
        //logging code
        return null;
    }

    return temporaryPdfFilePath;
}

Respuestas a la pregunta(5)

Su respuesta a la pregunta