c# - 使用 `InsertFile` 并在 IIS 上保存来自网站的文件

标签 c# ms-word ms-office com-interop

我想在word文档中添加一个文件

application.Selection.InsertFile(file);

但它会导致异常

COMException: The document name or path is not valid

然后保存

document.SaveAs(path);

但是我得到了异常

The object invoked has disconnected from its clients. (Exception HRESULT: 0x80010108 (RPC_E_DISCONNECTED))

完全相同的代码从 Visual Studio 运行时有效。 异常 仅在我尝试从 IIS 运行时发生。

会不会跟某些权限有关?我已将完全控制权限授予 EveryoneISUSRNetworkNetwork ServiceSystem, Administrators...我还尝试使用具有管理员帐户的 Impersonate。

我如何修复它以便它在我从 IIS 运行时正常工作?


这是我为操作文档而创建的类:http://pastebin.com/yB2s0jn4

我是这样调用它的

using (var doc = new HtmlWordDocument(outFile))
{
    // calls Selection.InsertFile( file )
    doc.WriteContent(tempFile);

    // calls document.SaveAs()
    doc.Save();
}

最佳答案

您是否尝试过模拟 (How to implement impersonation in an ASP.NET application)?如下所示:

System.Security.Principal.WindowsImpersonationContext impersonationContext;
impersonationContext = 
    ((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();

    using (var doc = new HtmlWordDocument(outFile))
    {
        // calls Selection.InsertFile( file )
        doc.WriteContent(tempFile);

        // calls document.SaveAs()
        doc.Save();
    }

impersonationContext.Undo();

关于c# - 使用 `InsertFile` 并在 IIS 上保存来自网站的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8260885/

相关文章:

c# - 有没有办法以编程方式将数字签名添加到 word 文档中的 VBA 宏?

c# - 在 System.Diagnostics.Trace 中获取 DateTime 的本地时间

c# - 我如何以编程方式(使用反射?)更改方法体并将我的更改保存回磁盘

C# DocX : Inserting new numbered list continues numbering

vba - 在 VBA 中创建和使用命名互斥体

vba - VBA Debug.Print 记录到哪里?

c# - mono 的逆变编译异常

c# - 以对象和成员名称作为参数的通用函数?

MS word 的 VBA

c++ - 在没有 MFC 或 ATL 的情况下,如何在 C++ 中找到 Office 传出 COM 接口(interface)的 IID?