saving word document as pdf using Interop results in COMException: command failed

270 Views Asked by At

I have an ASP.NET MVC app which application pool is configured to run as a custom identity account, for example, MyDomain\MyUser.

I have a problem when creating a pdf file from a word docx file: I get a "COMException command failed" when trying to save file as pdf to a temporary folder within app folder: C:\inetpub\wwwroot\MyAspNetMvcApp\Data\Documents\Temp

I have added the application pool custom identity account (MyDomain\MyUser) to the app folder with full control permissions but it does not work, there is no way to save pdf into app folder.

I have debugged it using process monitor on the server to handle incomings file system events from app folder, and I can see that when using SaveAs2 method provided from Interop, WINWORD.EXE on the server is called/executed but using the domain user account that is logged in the client machine instead of using the application pool custom identity account (MyDomain\MyUser), so when trying to write the new pdf file to C:\inetpub\wwwroot\MyAspNetMvcApp\Data\Documents\Temp the exception "COMException command failed" is thrown because it has no rights to write there.

I have set Identity as "The interactive user" for Microsoft Word DCOM Component.

Since application pool custom identity account has rights to write to that app folder, how can I force to execute Interop SaveAs2 method using the application pool custom identity account?

Below the code snippet:

public void ConvertToPDF(string myDocFile)
{
    // myDocFile contains "C:\\inetpub\\wwwroot\\MyAspNetMvcApp\\Data\\Documents\\Temp\\myDocxFile.docx"
    Document myDoc = GetMyDoc(myDocFile);

    string myPdfFile = Path.Combine(Path.GetDirectoryName(myDocFile), Path.GetFileNameWithoutExtension(myDocFile) + ".pdf");

    // myPdfFile now contains: "C:\\inetpub\\wwwroot\\MyAspNetMvcApp\\Data\\Documents\\Temp\\myPdfFile.pdf"

    // How can I force below SaveAs2 method to execute using the application pool custom account (the same account which runs w3wp.exe)?
    myDoc.SaveAs2(myPdfFile, WdSaveFormat.wdFormatPDF); // <--- HERE IT CRASHES: COMException command failed!!
    
    ...
}

public Document GetMyDoc(object docfile)
{
   // docFile contains "C:\\inetpub\\wwwroot\\MyAspNetMvcApp\\Data\\Documents\\Temp\\myDocxFile.docx"

   Application wApp = new Microsoft.Office.Interop.Word.Application();
   Document myDoc = wApp.Documents.Open(ref docFile);
   
   return myDoc;
}
0

There are 0 best solutions below