C# Microsoft.Office.Interop.Word-Word在尝试打开文件时遇到错误

C# Microsoft.Office.Interop.Word-Word在尝试打开文件时遇到错误,c#,asp.net,C#,Asp.net,我们有一个ASP.Net Web应用程序C,它正在通过Microsoft.Office.Interop.Word打开Word文件 首先,我意识到这不是推荐的方法,应该考虑使用TextControl或Asppose这样的库,我们将考虑使用这样的库来替代Microsoft.Office.Interop.Word 然而,在短期内,我想让它工作,我们的代码是在我的开发机器上工作,客户端的测试服务器,而不是他们的UAT服务器 客户端的测试服务器和UAT服务器看起来是一样的,我试着毫无乐趣地查看各种DCOM

我们有一个ASP.Net Web应用程序C,它正在通过Microsoft.Office.Interop.Word打开Word文件

首先,我意识到这不是推荐的方法,应该考虑使用TextControl或Asppose这样的库,我们将考虑使用这样的库来替代Microsoft.Office.Interop.Word

然而,在短期内,我想让它工作,我们的代码是在我的开发机器上工作,客户端的测试服务器,而不是他们的UAT服务器

客户端的测试服务器和UAT服务器看起来是一样的,我试着毫无乐趣地查看各种DCOM配置设置

我在Microsoft.Office.Interop.Word上查看了其他堆栈溢出问题,但这些建议都没有帮助

为了帮助测试这个问题,我编写了一个简单的测试应用程序,它试图使用下面的代码打开Word文档

var wordApplication = new Application();            
var wordDocument = wordApplication.Documents.Open(txtPath.Text);
wordApplication.Visible = true;
当运行Word进程时,任务管理器中会出现以下错误。我显然已经检查了文件权限等。欢迎任何建议


下面的演示项目演示如何将Word文档文件上载到web服务器,然后使用Microsoft.Office.Interop.Word读取该文件

先决条件:

MS Word安装在Web服务器计算机上。打开Word以确保不会出现任何消息框,例如Microsoft Word不是您查看和编辑文档的默认程序。。。 网站包含一个名为“上载”的文件夹 创建ASP.NET Web应用程序

与2017年相比:

开放式Visual Studio 扩展已安装 扩展visualc 点击网页 选择ASP.NET Web应用程序.NET Framework 单击“确定” 选择空 单击“确定” 与2019年相比:

开放式Visual Studio 单击不带代码的继续 单击文件 选择新的 选择项目 C Windows Web 单击ASP.NET Web应用程序.NET Framework 单击下一步 指定项目名称:AspNetWebApp2 单击创建 单击清空 取消选中Configure for HTTPS 单击创建 注:从这一点来看,2017年和2019年的流程是相同的

添加网络表单:

在VS菜单中,单击项目 选择添加新项目 选择Web表单名称:default.aspx 单击添加 打开解决方案资源管理器

在VS菜单中,单击查看 选择解决方案资源管理器 在解决方案资源管理器中,双击default3.aspx。将代码替换为以下内容:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using Word = Microsoft.Office.Interop.Word;

namespace AspNetWebApp2
{
    public partial class Default3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        protected void btnsave_Click(object sender, EventArgs e)
        {
            bool isVisible = true;
            StringBuilder sb = new StringBuilder();
            Word.Application wordApp = null;
            Word.Document doc = null;
            Word.Documents documents = null;

            if (FileUpload1.HasFile)
            {
                try
                {
                    sb.AppendFormat(" Uploading file: {0}", FileUpload1.FileName);

                    //saving the file

                    string localDir = System.IO.Path.Combine(Server.MapPath("."), "Uploads");

                    if (!System.IO.Directory.Exists(localDir))
                    {
                        string errMsg = String.Format("<script>alert('Error - Folder does not exist ({0})');</script>", localDir.Replace(@"\",@"\\"));
                        Response.Write(errMsg);
                    }

                    string localFn = System.IO.Path.Combine(Server.MapPath("."), "Uploads", FileUpload1.FileName);
                    FileUpload1.SaveAs(localFn);

                    //Showing the file information
                    sb.AppendFormat("<br/> Save As: {0}", FileUpload1.PostedFile.FileName);
                    sb.AppendFormat("<br/> File type: {0}", FileUpload1.PostedFile.ContentType);
                    sb.AppendFormat("<br/> File length: {0}", FileUpload1.PostedFile.ContentLength);
                    sb.AppendFormat("<br/> File name: {0}", FileUpload1.PostedFile.FileName);

                    wordApp = new Word.Application();

                    //suppress displaying alerts (such as prompting to overwrite existing file)
                    wordApp.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;

                    //set Word visibility
                    //wordApp.Visible = false;
                    wordApp.Visible = isVisible;

                    if (wordApp != null)
                    {
                        if (File.Exists(localFn))
                        {
                            StringBuilder sbData = new StringBuilder();

                            doc = wordApp.Documents.Open(localFn, System.Reflection.Missing.Value, false, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, isVisible, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
                            //doc = documents.Open(localFn);

                            doc.Activate();

                            foreach (Word.Paragraph p in doc.Content.Paragraphs)
                            {
                                Debug.WriteLine(p.Range.Text);
                                //Response.Write(p.Range.Text);
                                sbData.AppendLine(p.Range.Text);
                            }

                            textBoxData.Text = sbData.ToString();
                        }
                        else
                        {
                            Debug.WriteLine("Error: Filename '" + localFn + "' doesn't exist.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    sb.Append("<br/> Error <br/>");
                    sb.AppendFormat("Unable to save file <br/> {0}", ex.Message);
                }
                finally
                {
                    if (doc != null)
                    {
                        doc.Close();
                    }

                    if (documents != null)
                    {
                        documents.Close();
                    }

                    if (wordApp != null)
                    {
                        wordApp.Quit();
                        wordApp = null;
                    }
                }
            }
            else
            {
                lblmessage.Text = sb.ToString();
            }

            Debug.WriteLine(sb.ToString());
        }
    }
}
default3.aspx

添加引用Microsoft Word xx.0对象库

在VS菜单中,单击项目 选择添加引用 扩展COM 检查Microsoft Word xx.0对象库例如:Microsoft Word 16.0对象库 在解决方案资源管理器中,双击default3.aspx.cs并将代码替换为以下内容:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using Word = Microsoft.Office.Interop.Word;

namespace AspNetWebApp2
{
    public partial class Default3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        protected void btnsave_Click(object sender, EventArgs e)
        {
            bool isVisible = true;
            StringBuilder sb = new StringBuilder();
            Word.Application wordApp = null;
            Word.Document doc = null;
            Word.Documents documents = null;

            if (FileUpload1.HasFile)
            {
                try
                {
                    sb.AppendFormat(" Uploading file: {0}", FileUpload1.FileName);

                    //saving the file

                    string localDir = System.IO.Path.Combine(Server.MapPath("."), "Uploads");

                    if (!System.IO.Directory.Exists(localDir))
                    {
                        string errMsg = String.Format("<script>alert('Error - Folder does not exist ({0})');</script>", localDir.Replace(@"\",@"\\"));
                        Response.Write(errMsg);
                    }

                    string localFn = System.IO.Path.Combine(Server.MapPath("."), "Uploads", FileUpload1.FileName);
                    FileUpload1.SaveAs(localFn);

                    //Showing the file information
                    sb.AppendFormat("<br/> Save As: {0}", FileUpload1.PostedFile.FileName);
                    sb.AppendFormat("<br/> File type: {0}", FileUpload1.PostedFile.ContentType);
                    sb.AppendFormat("<br/> File length: {0}", FileUpload1.PostedFile.ContentLength);
                    sb.AppendFormat("<br/> File name: {0}", FileUpload1.PostedFile.FileName);

                    wordApp = new Word.Application();

                    //suppress displaying alerts (such as prompting to overwrite existing file)
                    wordApp.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;

                    //set Word visibility
                    //wordApp.Visible = false;
                    wordApp.Visible = isVisible;

                    if (wordApp != null)
                    {
                        if (File.Exists(localFn))
                        {
                            StringBuilder sbData = new StringBuilder();

                            doc = wordApp.Documents.Open(localFn, System.Reflection.Missing.Value, false, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, isVisible, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
                            //doc = documents.Open(localFn);

                            doc.Activate();

                            foreach (Word.Paragraph p in doc.Content.Paragraphs)
                            {
                                Debug.WriteLine(p.Range.Text);
                                //Response.Write(p.Range.Text);
                                sbData.AppendLine(p.Range.Text);
                            }

                            textBoxData.Text = sbData.ToString();
                        }
                        else
                        {
                            Debug.WriteLine("Error: Filename '" + localFn + "' doesn't exist.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    sb.Append("<br/> Error <br/>");
                    sb.AppendFormat("Unable to save file <br/> {0}", ex.Message);
                }
                finally
                {
                    if (doc != null)
                    {
                        doc.Close();
                    }

                    if (documents != null)
                    {
                        documents.Close();
                    }

                    if (wordApp != null)
                    {
                        wordApp.Quit();
                        wordApp = null;
                    }
                }
            }
            else
            {
                lblmessage.Text = sb.ToString();
            }

            Debug.WriteLine(sb.ToString());
        }
    }
}
资源:


下面的演示项目演示如何将Word文档文件上载到web服务器,然后使用Microsoft.Office.Interop.Word读取该文件

先决条件:

MS Word安装在Web服务器计算机上。打开Word以确保不会出现任何消息框,例如Microsoft Word不是您查看和编辑文档的默认程序。。。 网站包含一个名为“上载”的文件夹 创建ASP.NET Web应用程序

与2017年相比:

开放式Visual Studio 扩展已安装 扩展visualc 点击网页 选择ASP.NET Web应用程序.NET Framework 单击“确定” 选择空 单击“确定” 与2019年相比:

开放式Visual Studio 单击不带代码的继续 单击文件 选择新的 选择项目 C Windows Web 单击ASP.NET Web应用程序.NET Framework 单击下一步 指定项目名称:AspNetWebApp2 单击创建 单击清空 取消选中Configure for HTTPS 单击创建 注:从这一点来看,2017年和2019年的流程是相同的

添加网络表单:

在VS菜单中,单击项目 选择添加新项目 选择Web表单名称:default.aspx 单击添加 打开解决方案资源管理器

在VS菜单中,单击查看 选择解决方案资源管理器 在解决方案资源管理器中,双击default3.aspx。将代码替换为以下内容:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using Word = Microsoft.Office.Interop.Word;

namespace AspNetWebApp2
{
    public partial class Default3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        protected void btnsave_Click(object sender, EventArgs e)
        {
            bool isVisible = true;
            StringBuilder sb = new StringBuilder();
            Word.Application wordApp = null;
            Word.Document doc = null;
            Word.Documents documents = null;

            if (FileUpload1.HasFile)
            {
                try
                {
                    sb.AppendFormat(" Uploading file: {0}", FileUpload1.FileName);

                    //saving the file

                    string localDir = System.IO.Path.Combine(Server.MapPath("."), "Uploads");

                    if (!System.IO.Directory.Exists(localDir))
                    {
                        string errMsg = String.Format("<script>alert('Error - Folder does not exist ({0})');</script>", localDir.Replace(@"\",@"\\"));
                        Response.Write(errMsg);
                    }

                    string localFn = System.IO.Path.Combine(Server.MapPath("."), "Uploads", FileUpload1.FileName);
                    FileUpload1.SaveAs(localFn);

                    //Showing the file information
                    sb.AppendFormat("<br/> Save As: {0}", FileUpload1.PostedFile.FileName);
                    sb.AppendFormat("<br/> File type: {0}", FileUpload1.PostedFile.ContentType);
                    sb.AppendFormat("<br/> File length: {0}", FileUpload1.PostedFile.ContentLength);
                    sb.AppendFormat("<br/> File name: {0}", FileUpload1.PostedFile.FileName);

                    wordApp = new Word.Application();

                    //suppress displaying alerts (such as prompting to overwrite existing file)
                    wordApp.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;

                    //set Word visibility
                    //wordApp.Visible = false;
                    wordApp.Visible = isVisible;

                    if (wordApp != null)
                    {
                        if (File.Exists(localFn))
                        {
                            StringBuilder sbData = new StringBuilder();

                            doc = wordApp.Documents.Open(localFn, System.Reflection.Missing.Value, false, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, isVisible, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
                            //doc = documents.Open(localFn);

                            doc.Activate();

                            foreach (Word.Paragraph p in doc.Content.Paragraphs)
                            {
                                Debug.WriteLine(p.Range.Text);
                                //Response.Write(p.Range.Text);
                                sbData.AppendLine(p.Range.Text);
                            }

                            textBoxData.Text = sbData.ToString();
                        }
                        else
                        {
                            Debug.WriteLine("Error: Filename '" + localFn + "' doesn't exist.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    sb.Append("<br/> Error <br/>");
                    sb.AppendFormat("Unable to save file <br/> {0}", ex.Message);
                }
                finally
                {
                    if (doc != null)
                    {
                        doc.Close();
                    }

                    if (documents != null)
                    {
                        documents.Close();
                    }

                    if (wordApp != null)
                    {
                        wordApp.Quit();
                        wordApp = null;
                    }
                }
            }
            else
            {
                lblmessage.Text = sb.ToString();
            }

            Debug.WriteLine(sb.ToString());
        }
    }
}
default3.aspx

添加引用Microsoft Word xx.0对象库

在VS菜单中,单击项目 选择添加引用 扩展COM 检查Microsoft Word xx.0对象库例如:Microsoft Word 16.0对象库 在解决方案资源管理器中,双击default3.aspx.cs并将代码替换为以下内容:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using Word = Microsoft.Office.Interop.Word;

namespace AspNetWebApp2
{
    public partial class Default3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        protected void btnsave_Click(object sender, EventArgs e)
        {
            bool isVisible = true;
            StringBuilder sb = new StringBuilder();
            Word.Application wordApp = null;
            Word.Document doc = null;
            Word.Documents documents = null;

            if (FileUpload1.HasFile)
            {
                try
                {
                    sb.AppendFormat(" Uploading file: {0}", FileUpload1.FileName);

                    //saving the file

                    string localDir = System.IO.Path.Combine(Server.MapPath("."), "Uploads");

                    if (!System.IO.Directory.Exists(localDir))
                    {
                        string errMsg = String.Format("<script>alert('Error - Folder does not exist ({0})');</script>", localDir.Replace(@"\",@"\\"));
                        Response.Write(errMsg);
                    }

                    string localFn = System.IO.Path.Combine(Server.MapPath("."), "Uploads", FileUpload1.FileName);
                    FileUpload1.SaveAs(localFn);

                    //Showing the file information
                    sb.AppendFormat("<br/> Save As: {0}", FileUpload1.PostedFile.FileName);
                    sb.AppendFormat("<br/> File type: {0}", FileUpload1.PostedFile.ContentType);
                    sb.AppendFormat("<br/> File length: {0}", FileUpload1.PostedFile.ContentLength);
                    sb.AppendFormat("<br/> File name: {0}", FileUpload1.PostedFile.FileName);

                    wordApp = new Word.Application();

                    //suppress displaying alerts (such as prompting to overwrite existing file)
                    wordApp.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;

                    //set Word visibility
                    //wordApp.Visible = false;
                    wordApp.Visible = isVisible;

                    if (wordApp != null)
                    {
                        if (File.Exists(localFn))
                        {
                            StringBuilder sbData = new StringBuilder();

                            doc = wordApp.Documents.Open(localFn, System.Reflection.Missing.Value, false, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, isVisible, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
                            //doc = documents.Open(localFn);

                            doc.Activate();

                            foreach (Word.Paragraph p in doc.Content.Paragraphs)
                            {
                                Debug.WriteLine(p.Range.Text);
                                //Response.Write(p.Range.Text);
                                sbData.AppendLine(p.Range.Text);
                            }

                            textBoxData.Text = sbData.ToString();
                        }
                        else
                        {
                            Debug.WriteLine("Error: Filename '" + localFn + "' doesn't exist.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    sb.Append("<br/> Error <br/>");
                    sb.AppendFormat("Unable to save file <br/> {0}", ex.Message);
                }
                finally
                {
                    if (doc != null)
                    {
                        doc.Close();
                    }

                    if (documents != null)
                    {
                        documents.Close();
                    }

                    if (wordApp != null)
                    {
                        wordApp.Quit();
                        wordApp = null;
                    }
                }
            }
            else
            {
                lblmessage.Text = sb.ToString();
            }

            Debug.WriteLine(sb.ToString());
        }
    }
}
资源:


最后,我的问题在遵循上概述的步骤后得到了解决

我在用户组中创建了一个新用户,名为WordUser 我已在IIS中创建了具有WordUser权限的新应用程序池;加载用户配置文件必须为true DCOM我已设置为使用WordUser,在“安全”选项卡上,我添加了具有启动和激活权限以及访问权限的WordUser
结果表明,创建本地用户kick似乎启动了一些事情,就好像我将应用程序切换为使用以前的应用程序池,并将DCOM设置为使用以前指定的用户一样。我的应用程序正常工作。

最后,我的问题在遵循上概述的步骤后得到了解决

我有c 已在用户组中创建名为WordUser的新用户 我已在IIS中创建了具有WordUser权限的新应用程序池;加载用户配置文件必须为true DCOM我已设置为使用WordUser,在“安全”选项卡上,我添加了具有启动和激活权限以及访问权限的WordUser
结果显示,似乎本地用户的创建启动了一些事情,就好像我将应用程序切换为使用以前的应用程序池,并将DCOM设置为使用以前指定的用户一样。我的应用程序工作。

假设文件存在测试,它看起来像是权限错误,试图打开文件。你在某个地方主持你的MVC。您确信IIS用户有打开文档或访问目录的权限吗?您可以考虑使用NuGET包Debug TrimeMat.OpenXML。这篇文章可能也很有用:@Goodies它肯定会到达文件,就好像我通过一条不存在的路径一样,收到了另一条错误消息。我还添加了Everyone对该文件的权限,以再次检查该文件是否具有权限。@user9938-谢谢您将签出DocumentFormat.OpenXml。不幸的是,Microsoft.Office.Interop.Word的使用在该应用程序中非常普遍,因此,即使从长远来看,这是最好的方法,但调出也不是一项简单的任务。假设文件存在,则在尝试打开该文件时,看起来像是权限错误。你在某个地方主持你的MVC。您确信IIS用户有打开文档或访问目录的权限吗?您可以考虑使用NuGET包Debug TrimeMat.OpenXML。这篇文章可能也很有用:@Goodies它肯定会到达文件,就好像我通过一条不存在的路径一样,收到了另一条错误消息。我还添加了Everyone对该文件的权限,以再次检查该文件是否具有权限。@user9938-谢谢您将签出DocumentFormat.OpenXml。不幸的是,Microsoft.Office.Interop.Word的使用在该应用程序中非常普遍,因此,即使从长远来看这是最好的方法,也不会是一项微不足道的任务。您会发现,问题似乎已归结为应用程序池/DCOM级别的权限问题,但是此代码非常有用。非常感谢。您将看到,问题似乎已归结为应用程序池/DCOM级别的权限问题,但是此代码非常有用。非常感谢。