2013-06-18 25 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)

相关问题