首页 文章

错误进程无法访问该文件,因为它正由另一个进程使用

提问于
浏览
3

在这我试图将单词转换为pdf文件 . 但我得到一个错误"The process cannot access the file because it is being used by another process" .

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格式 .

5 回答

  • 2

    您需要做的是确定保持文件打开的进程 .

    要找到它,您需要从SysInternals(现在是Microsoft的一部分)下载Process Explorer .

    这将允许您搜索所有进程以找出哪些进程具有文件的打开句柄 .

    当然,可能是文件冲突与不太明显的文件(例如配置或锁定文件)有关 . 在这种情况下,Process Monitor(也来自SysInternals)应该允许您查看失败的内容 .

    两者都是很棒的工具,一旦你使用它们,它们就会成为你军械库的一部分 .

  • 0

    如果您第一次运行代码 - 显然文件没有正确处理's possible will be okay. But it' . Standart .net GC无法正确处理 Interop 对象 . 所以,几点提示:
    1)不要使用 Interop.Word.DocumentInterop.Word.Application 创建公共属性 . 在您的方法中使用它们并尽快处理 .
    2)关闭 Application ASAP的第二个原因是RPC服务器已超时 . 如果您保持 Application 打开一段时间,它将自动从RPC服务器断开连接,您将无法使用它 .

    考虑到这一点,你必须在 finally 语句中调用 apword.Quit(); ,而不是在 catch 中单独使用 apword = null 是不够的 .
    如果应用程序已关闭并出现错误 - 肯定会终止单词进程 .
    并且在离开方法之前不要忘记调用 wordDocuments.Close(ref SaveChanges) .

  • -2

    该变量包含带扩展名的文件名,因此您尝试将文档保存在打开的文档上 . 添加一个axtension:

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

    我猜那行File.Delete(targetPathip);不是问题,可能是第二次运行,因为应用程序在第一次运行时保持文件打开(请参阅任务管理器) .

  • -1

    有这样的问题一次,在打开之前尝试关闭你的文件(听起来很愚蠢,但对我有用......) .

    apword.Documents.Close(Filename_path);
    wordDocuments = apword.Documents.Open(Filename_path);
    
  • -1

    你只需要添加

    using System.Threading;
    

    在cs页面的顶部..并添加

    Thread.SpinWait(6000);
    

    在文本顶部显示错误 .

    试试这个,如果你需要任何帮助告诉我 .

相关问题