在此我试图将单词转换为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;
}
转换时我的代码中是否有任何遗漏?任何人都可以告诉我如何将单词转换为PDF格式。
答案 0 :(得分:2)
您需要做的是确定保持文件打开的过程。
要找到这个,您需要从SysInternals(现在是Microsoft的一部分)下载Process Explorer。
这将允许您搜索所有进程,以找出哪些进程具有文件的打开句柄。
当然可能是文件冲突与不太明显的文件(如配置或锁定文件)有关。在这种情况下,Process Monitor(也来自SysInternals)应该允许您查看失败的内容。
两者都是出色的工具,一旦你使用它们,它们就会成为你军械库的一部分。
答案 1 :(得分:0)
如果您是第一次运行代码 - 它可能会正常运行。但很明显,文件处理不当。 Standart .net GC 无法正确处理Interop
个对象。所以,几点提示:
1)不要使用Interop.Word.Document
或Interop.Word.Application
创建公共属性。在您的方法中使用它们并尽快处理
2)关闭Application
ASAP的第二个原因是RPC服务器已超时。如果您将Application
保持打开一段时间,它将自动与RPC服务器断开连接,您将无法使用它。
考虑到这一点,您必须在apword.Quit();
声明中致电finally
,而不是catch
而仅apword = null
并不足够。
如果应用程序已关闭并出现错误 - 请确保终止字处理。
在离开方法之前不要忘记给wordDocuments.Close(ref SaveChanges)
打电话。
答案 2 :(得分:-1)
变量包含带扩展名的文件名,因此您尝试将文档保存在打开的文档上。添加一个axtension:
wordDocuments.ExportAsFixedFormat(Filename_path + ".pdf",
WdExportFormat.wdExportFormatPDF);
我想行 File.Delete(targetPathip); 不是问题,可能是第二次运行,因为应用程序在第一次运行时保持文件打开(请参阅任务管理器)。
答案 3 :(得分:-1)
遇到这样的问题,在打开之前尝试关闭你的文件(听起来很愚蠢,但对我有用......)。
apword.Documents.Close(Filename_path);
wordDocuments = apword.Documents.Open(Filename_path);
答案 4 :(得分:-2)
你只需要添加
using System.Threading;
位于cs页面的顶部.. 并添加
Thread.SpinWait(6000);
位于文本顶部,显示错误。
试试这个,如果你需要任何帮助,请告诉我。