如何在C#中使用Word文档

时间:2012-04-11 14:25:14

标签: c# asp.net-mvc reference ms-word

我有一个问题,起初似乎是许可。 在localhost上工作正常但在发生服务器时出错:

  

[UnauthorizedAccessException:检索COM类工厂   CLSID为{000209FF-0000-0000-C000-000000000046}的组件失败   至以下错误:80070005。]

我使用IIS7
我给了iis用户许可,但无济于事,然后我在代码中传播“try catch”,发现错误与它尝试创建Microsoft.Office.Interop.Word实例的时刻有关

例如

using Word = Microsoft.Office.Interop.Word;

private bool Exemple(SqlDataReader dbReader, string strFilePath)
{ 
    Word.Application oApp = new Word.Application ();   // error here
    ...
    ...
    ...
}

Microsoft.Office.Interop.Word这个dll在服务器的Bin文件夹中,有没有人知道可能会发生什么?

谢谢。

3 个答案:

答案 0 :(得分:4)

虽然您不应在服务器上使用Office互操作库。 Microsoft不建议或支持这种实现,但是如果您要求惩罚以解决错误,则需要在服务器上打开DCOM配置并将身份设置为您的应用程序池正在运行的用户并授予他们访问启动和激活权限。同样,您不希望在服务器上设置Office互操作库。

答案 1 :(得分:0)

(虽然不建议在服务器中使用office interop,但有时我们必须......)

该问题与安全性有关。 ASP.NET进程的用户标识没有使用Office应用程序的访问权限,并且标识应该只具有运行应用程序所需的最小权限。您可以使用代码模拟在运行时提升权限,而无需在web.config中设置Impersonation或为我的ASP.NET用户帐户使用高权限帐户。我在服务器中使用它,我喜欢这种方法。

您可以google了解更多信息。 以下是http://support.microsoft.com/kb/306158的代码:

public class CodeImpersonate
{
    /// <summary>
    /// This logon type is intended for users who will be interactively using the computer, such as a user being logged on by a terminal server, 
    /// remote shell, or similar process. This logon type has the additional expense of caching logon information for disconnected operations; therefore,
    /// it is inappropriate for some client/server applications, such as a mail server.
    /// </summary>
    public const int LOGON32_LOGON_INTERACTIVE = 2;
    /// <summary>
    /// Use the standard logon provider for the system. The default security provider is negotiate, 
    /// unless you pass NULL for the domain name and the user name is not in UPN format. In this case, the default provider is NTLM.
    /// Windows 2000: The default security provider is NTLM.
    /// </summary>
    public const int LOGON32_PROVIDER_DEFAULT = 0;

    WindowsImpersonationContext impersonationContext;

    [DllImport("advapi32.dll")]
    public static extern int LogonUserA(String lpszUserName,
                                        String lpszDomain,
                                        String lpszPassword,
                                        int dwLogonType,
                                        int dwLogonProvider,
                                        ref IntPtr phToken);

    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern int DuplicateToken(IntPtr hToken, int impersonationLevel, ref IntPtr hNewToken);

    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern bool RevertToSelf();

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public static extern bool CloseHandle(IntPtr handle);      

    public bool ImpersonateValidUser(String userName, String domain, String password)
    {
        WindowsIdentity tempWindowsIdentity;
        IntPtr token = IntPtr.Zero;
        IntPtr tokenDuplicate = IntPtr.Zero;

        if (RevertToSelf())
        {
            if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
            {
                if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                {
                    tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                    impersonationContext = tempWindowsIdentity.Impersonate();
                    if (impersonationContext != null)
                    {
                        CloseHandle(token);
                        CloseHandle(tokenDuplicate);
                        return true;
                    }
                }
            }
        }
        if (token != IntPtr.Zero)
            CloseHandle(token);
        if (tokenDuplicate != IntPtr.Zero)
            CloseHandle(tokenDuplicate);
        return false;
    }

    public void UndoImpersonation()
    {
        if (impersonationContext != null)
            impersonationContext.Undo();
    }

}

将上述代码复制到文件中。以下是它的使用示例:

CodeImpersonate codeImpersonate = null;
try
{
    codeImpersonate = new CodeImpersonate();
    var isLoggedIn = codeImpersonate.ImpersonateValidUser(AppConfigs.OfficeUser, AppConfigs.OfficeUeerDomnia, AppConfigs.OfficeUserPass);

    if (isLoggedIn)
    {
        //Do your office work....
    }
    else
        throw new InvalidOperationException("Login failed for office user.");
}
finally
{
    if (codeImpersonate != null)
        codeImpersonate.UndoImpersonation();
    codeImpersonate = null;
}

要在多个地方使用上述代码,这是一个外观:

public class ImpersonateServices
{
    public ImpersonateServices(String userName, String domain, String password)
    {
        this.UserName = userName;
        this.Domain = domain;
        this.Password = password;
    }

    public string UserName { get; private set; }

    public string Domain { get; private set; }

    public string Password { get; private set; }

    public void Execute(Action privilegedAction)
    {
        CodeImpersonate codeImpersonate = null;
        try
        {
            codeImpersonate = new CodeImpersonate();
            var isLoggedIn = codeImpersonate.ImpersonateValidUser(this.UserName, this.Domain, this.Password);

            if (isLoggedIn){
                privilegedAction();
            }
            else
                throw new InvalidOperationException("Login failed for office user.");
        }
        finally
        {
            if (codeImpersonate != null)
                codeImpersonate.UndoImpersonation();
            codeImpersonate = null;
        }
    }
}

使用它像:

var impersonateServices = new ImpersonateServices(AppConfigs.OfficeUser, 
                                              AppConfigs.OfficeUserDomain, 
                                              AppConfigs.OfficeUserPass);
impersonateServices.Execute(() => { 
    //Do your Office work...
});

office-User 应该是有效的本地或域帐户。 要测试办公室用户帐户是否正常工作,请使用此用户帐户凭据登录服务器并启动MS Word应用程序。如果Word是第一次打开,可能会出现一些与弹出窗口相关的设置。解决它们,否则它们可能会在程序化访问期间产生问题。

如果您在配置文件中保留用户帐户凭据,请考虑加密这些值。见下面的SO Q&amp; A:

How to encrypt one entry in web.config

Encrypting appSettings in web.config

希望这会有所帮助......

答案 2 :(得分:0)

在IIS中的Application Pools下,将Identity字段设置为NetworkService可在我的设置中解决此问题。