在.net中使用c#应用程序实现msword自动化,或在资源已被使用时抛出

在.net中使用c#应用程序实现msword自动化,或在资源已被使用时抛出,c#,.net,C#,.net,我正在使用mergefield和bookmark处理word文档。该应用程序在调试模式下运行良好,但在发布模式下出错。我是word automation的新手。请帮助。如果需要任何其他详细信息,请告诉我。下面给出了源代码 > Blockquote object nothing = System.Reflection.Missing.Value; object filename = "E:\\Templatenew.doc"; object destinat

我正在使用mergefield和bookmark处理word文档。该应用程序在调试模式下运行良好,但在发布模式下出错。我是word automation的新手。请帮助。如果需要任何其他详细信息,请告诉我。下面给出了源代码

> Blockquote
 object nothing = System.Reflection.Missing.Value;
        object filename = "E:\\Templatenew.doc";
        object destination = "E:\\new.doc";
        object nottrue = false; 

        object oPrintdate = "printdate";
        object oClientname = "clientname";
        object oClientsname = "clientsname";
        object oAsondate = "asondate";
        object oAmount = "amount";



        myWordApp.Visible = false;
        myWordDoc = myWordApp.Documents.Add(ref filename, ref nothing, ref nothing, ref nothing);

        myWordDoc.Activate();

        myWordDoc.Bookmarks.get_Item(ref oPrintdate).Range.Text = System.DateTime.Now.ToShortDateString();
        myWordDoc.Bookmarks.get_Item(ref oClientname).Range.Text = objproperty.firstname +"" + objproperty.lastname;

        myWordDoc.Bookmarks.get_Item(ref oAmount).Range.Text = "10000";



        myWordDoc.SaveAs(ref destination, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing,
                            ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing);
        myWordDoc.Close(ref destination, ref filename, ref nothing);



        Response.ContentType = "application/msword";
        myWordApp.Application.Quit(ref nottrue, ref nothing, ref nothing);

        Response.WriteFile("E:\\new.doc");
        Response.End();

> Blockquote

您没有正确处理Word对象。这将阻止自动Word进程退出--如果打开Task Manager,您将看到仍在运行的winword.exe进程。可能至少有一个进程锁定了您的新.doc文件

查看下面的链接,了解如何正确引用和处置Word对象。简言之:

  • 永远不要对COM对象使用2个点——始终为引用的任何对象属性创建单独的变量引用。(例如,您应该执行
    var Documents=myWordApp.Documents;Documents.Add…
    ,而不是
    myWordApp.Documents.Add…)
  • 在可能的情况下,在使用完引用的所有COM对象后,对其调用Close/Quit方法。(我想你已经在这么做了。)
  • 通过将每个引用设置为
    null
    并调用适当的垃圾收集方法,正确处理所有引用的COM对象。(见第二链接)
(这涉及Excel自动化,但仍适用于Word。)

运行应用程序后,请确保任务管理器中没有winword.exe进程挂起


(顺便说一句,你必须非常小心地使用Word automation。stackoverflow上的许多人会简单地告诉你永远不要这样做。根据我的经验,只要你遵守上述规则,并尽可能短地打开Word进程,你就可以这样做。我已经在一个流量适中的网站上使用了一年多t没有一个问题。)

不要在服务器上自动运行Word。这将导致严重的问题,包括此问题。确切的错误消息是什么,它是从哪一行抛出的?new.doc是否可能已被其他进程打开?检查winword.exe进程是否仍在运行。“Word无法保存此文件,因为它已在其他位置打开。”这是错误消息