2013-06-18 57 views
3

在此我試圖將word轉換爲pdf文件。但我得到一個錯誤 「該進程無法訪問該文件,因爲它正在被另一個進程使用」。錯誤進程無法訪問該文件,因爲它正在被另一個進程使用

public Microsoft.Office.Interop.Word.Document wordDocuments { get; set; } 

    Microsoft.Office.Interop.Word.Application apword = new Microsoft.Office.Interop.Word.Application(); 
    try 
    { 
     if (uploadFInput.HasFile) 
     { 
      targetPathip = Server.MapPath(Path.GetFileName(uploadFInput.PostedFile.FileName)); 

      if (File.Exists(targetPathip)) 
      { 
       File.Delete(targetPathip); 
      } 

      string Extentsion_path = Path.GetExtension(targetPathip); 
      string Filename_path = Path.GetFileName(targetPathip); 
      if (Extentsion_path == ".doc" || Extentsion_path == ".docx") 
      { 
       uploadFInput.SaveAs(targetPathip); 
       LblFleip.Text = targetPathip; 

       //wordDocuments = apword.Documents.Open(Filename_path); 
       wordDocuments = apword.Documents.Open(Filename_path); 
       // wordDocuments = apword.Documents.Open(targetPathip); 

       wordDocuments.ExportAsFixedFormat(Filename_path, WdExportFormat.wdExportFormatPDF); 
       apword.Documents.Close(Filename_path); 
      } 
      string filename = Path.GetFileName(targetPathip); 
      uploadFInput.SaveAs(targetPathip); 
      LblFleip.Text = targetPathip; 
     } 
    } 
    catch (Exception ex) 
    { 
     apword = null; 
     return; 
    } 

轉換時我的代碼中是否有缺失?任何人都可以告訴我如何將word轉換爲pdf。

+0

'wordDocuments = apword.Documents.Open(Filename_path).. wordDocuments.ExportAsFixedFormat(Filename_path,X)' - 相同的文件名*非常*可疑。 – user2246674

+1

@ user2246674它曾在Windows窗體中工作過相同的代碼.... – pdp

+1

當您運行此代碼時,實際的Word文檔不會在您的桌面上打開嗎? –

回答

-2

你只需要添加

using System.Threading; 

在CS頁面.. 的頂部和文本的頂部在那裏你展示一個錯誤添加

Thread.SpinWait(6000); 

試試這個,如果你需要任何幫助告訴我。

+2

我會建議反對這...看起來像它只會延遲問題 – Sayse

+1

@mitesh這隻會延遲它。如果pdf或單詞文件很大,這是困難的。 – pdp

+1

我同意@ sayse這將延遲 – pdp

-1

變量包含帶擴展名的文件名,所以您試圖將文檔保存在打開的文檔上。添加axtension:

wordDocuments.ExportAsFixedFormat(Filename_path + ".pdf", 
    WdExportFormat.wdExportFormatPDF); 

我想這行File.Delete(targetPathip);不是問題,可能是第二次運行,因爲應用程序將文件從第一次運行中打開(請參閱任務管理器)。

+0

我想知道這是否是第二次運行,如果發生這種情況,可以通過正確處置apword來解決 – Sayse

-1

遇到過這樣的問題,在打開之前嘗試關閉文件(聽起來很愚蠢,但對我工作...)。

apword.Documents.Close(Filename_path); 
wordDocuments = apword.Documents.Open(Filename_path); 
+0

異常:@ 3wic由於文檔窗口未處於活動狀態,因此此方法或屬性不可用。 – pdp

2

您需要做的是確定打開文件的過程。

爲了找到這個,你需要從SysInternals(現在是Microsoft的一部分)下載Process Explorer。

這將允許您搜索所有進程以找出哪些進程已打開處理您的文件。

當然,它可能是文件衝突與較不明顯的文件(如配置文件或鎖定文件)相關。在這種情況下,Process Monitor(也來自SysInternals)應該允許您查看失敗的情況。

兩者都是很棒的工具,一旦你使用了它們,它們將成爲你軍械庫的一部分。

0

如果您第一次運行代碼 - 可能會沒事的。但很明顯,文件沒有正確處理。 Standart .net GC不能在Interop對象上正常工作。所以,很少提示:
1)請勿使用Interop.Word.DocumentInterop.Word.Application製作公共物業。在你的方法中使用它們並儘快處置。
2)ASAP關閉Application的第二個原因是RPC服務器超時。如果您保留Application一段時間,它將自動與RPC服務器斷開連接,您將無法使用它。

有鑑於此,您必須在finally聲明中致電apword.Quit();聲明,而不是僅僅在catchapword = null是不夠的。
如果應用程序被錯誤關閉 - 肯定會殺死文字進程。
並且在離開方法之前不要忘記撥打wordDocuments.Close(ref SaveChanges)

相關問題