【问题标题】:C# open a pdf file using default application and delete the file after application is closedC#使用默认应用程序打开pdf文件并在应用程序关闭后删除文件
【发布时间】:2019-12-19 00:02:49
【问题描述】:

我正在将 .txt 文件转换为 pdf 文件,并且需要将 pdf 文件显示给用户。为此,我创建了一个临时 .pdf 文件并创建了一个打开文件的进程。当安装了 adobe acrobat 时,这可以正常工作。当没有默认应用程序时,这将失败。就我而言,pdf 在 Internet Explorer 中打开,我得到 No process is associated with this object 异常。有没有其他方法可以找出文件何时被关闭,以便我稍后删除它。

我的代码是这样的。

                HtmlToPdf htmlToPdf = new HtmlToPdf(pdfPrintOptions);

                string tmpFileName = "zx" + DateTime.Now.Ticks + "x.pdf";

                //Iron pdf does not handle in-memory pdf viewing
                //convert it to pdf
                htmlToPdf.RenderHTMLFileAsPdf(fileWithPath).SaveAs(tmpFileName);

                // TempFileCollection tmpFileCollection = new TempFileCollection();
                //Use windows process to open the file
                Process pdfViewerProcess = new Process
                {
                    EnableRaisingEvents = true, StartInfo = {FileName = tmpFileName}
                };
                pdfViewerProcess.Start();

                pdfViewerProcess.WaitForExit(); **Failing in this line**
                //Delete temporary file after the viewing windows is closed
                if (File.Exists(tmpFileName))
                {
                    File.Delete(tmpFileName);
                }

类似的问题似乎没有提供解决此问题的方法。任何帮助将不胜感激。谢谢。

【问题讨论】:

  • 打开的程序没有保存文件吗?你确定吗?

标签: c# ironpdf


【解决方案1】:

您必须在global variable 中定义tmpFileName 并使用Event 像这样退出:

try{
 Process myProcess = new Process();
 myProcess.StartInfo.FileName = tmpFileName;
 myProcess.EnableRaisingEvents = true;
 myProcess.Exited += new EventHandler(myProcess_Exited);
 myProcess.Start();
}
catch (Exception ex){
 //Handle ERROR
 return;
}


// Method Handle Exited event. 
private void myProcess_Exited(object sender, System.EventArgs e){
 if (File.Exists(tmpFileName))
    {
       File.Delete(tmpFileName);
    }
}

希望对你有帮助

更新我的答案: 如果还是不行。试试this answers

【讨论】:

  • 结果是一样的。当没有默认应用程序时(例如,如果 Internet Explorer 是您的默认 pdf 查看器,则不会触发 Exited 事件)。
  • 更新了我的答案
【解决方案2】:

我只是将 PDF 文件保存在 TEMP 文件夹中。

在 Windows 用户 TEMP 文件夹或您的应用程序中都可以创建一个 TEMP 文件夹。如果您创建一个 TEMP 文件夹,只需在您的应用关闭时删除所有文件。

string filePath = Path.GetTempPath() + "yourfile.pdf"; 

//Writer your file to Path
//File.WriteAllBytes(filePath, content);

Process.Start(filePath);

【讨论】:

  • 我正在考虑 TmpFileCollection 方法,但不知道如何从那里打开进程。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-07
  • 2019-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多