C#關閉word時,提示“此檔案正由另一個應用程式或使用者使用” normal.dot

來源:互聯網
上載者:User
由於項目需要將一個doc檔案轉換成一個html檔案,同時顯示在web頁面上.在項目開始前期時,做了Demo後,沒有發現什麼問題,到真正開始時,問題就來了!第一:在轉換成html檔案後,開啟html時,有時會提示檔案正在使用之類的,通過強大的Google得到的結果是說,由於記憶體沒有及時釋放(運行速度問題吧,因為我是有退出了word對象的),那我就讓當前程       序停留半秒Thread.Sleep(500);,果然,問題解決了.一切正常.第二:隔後以現,第二個問題又出現了,就是當你本地開啟了一個word程式(即使不同個檔案),然後再用C#去轉換成html,再開啟html時,又是報了一個正在使用之類的提示.這時就覺得奇怪了,我本地又沒有開啟頁面上開啟的檔案.最後發現,我只是退出,沒有關閉 關閉代碼:        object Unknown = Type.Missing;        docs.Close(ref Unknown, ref Unknown, ref Unknown);結束代碼:        wordtype.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, appclass, null);//退出 加上關閉後,勉強算是可以實現了,為啥說是勉強呢,因為在開啟之前頁面之前(就是轉換成html成功之後,要退出word的時候),會提示“此檔案正由另一個應用程式或使用者使用” c:\Documents and Settings..\normal.dot其實他大概的意思就是你更新了模板,要不要替換之類的吧!這時你開啟一個word,選擇"工具->模板->把自動更新樣式的勾去掉"就行了(網上是這樣說的,不過本人試了,公司的電腦這樣可以解決問題,但本人的筆記本不能解決),最後在ApplicationClass對象裡面,有一個可以儲存模板的屬性,只要將這個屬性設定成true就行了.//避免彈出normal.dot被使用的對話方塊,自動儲存模板wordApp.NormalTemplate.Saved = true; 下面是主要代碼//獲得word檔案的常值內容
        public string Word2Text(string docFileName)
        {
            //執行個體化COM
            Microsoft.Office.Interop.Word.ApplicationClass wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
            object fileobj = docFileName;
            object nullobj = System.Reflection.Missing.Value;
            //開啟指定檔案(不同版本的COM參數個數有差異,一般而言除第一個外都用nullobj就行了)
            Microsoft.Office.Interop.Word._Document doc = wordApp.Documents.Open(ref fileobj, ref nullobj, ref nullobj,
            ref nullobj, ref nullobj, ref nullobj,
            ref nullobj, ref nullobj, ref nullobj,
            ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj
            );
            //取得doc檔案中的文本
            string outText = doc.Content.Text;
            //避免彈出檔案(normal.dot)被使用的對話方塊,自動儲存模板
            wordApp.NormalTemplate.Saved = true;
            //關閉檔案
            doc.Close(ref nullobj, ref nullobj, ref nullobj);
            //關閉COM
            wordApp.Quit(ref nullobj, ref nullobj, ref nullobj);
            //返回
            return outText;
        }
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.