【问题标题】:Can't open PDF, is there a way to detect if it opens?无法打开 PDF,有没有办法检测它是否打开?
【发布时间】:2014-05-14 21:56:35
【问题描述】:

我正在编写一个 C# Windows 程序。在表格上,我有一个网站和 PDF 列表。当他们单击 PDF 时,代码会下载该文件,然后尝试打开它。在我的 Windows 8 机器上,PDF 可以正常打开。在 Windows 7 和 XP 机器上,它们没有打开,也没有视觉线索显示出问题所在。 (在这两台机器上,您都可以在文件资源管理器中单击 PDF,然后 PDF 将打开。)

我从查看Opening a pdf in .NET 开始,然后添加了它。这是我正在使用的...

if (File.Exists(localFileName))
{
    //MessageBox.Show("calling file " + localFileName, "FYI...");
    System.Diagnostics.Process process = new System.Diagnostics.Process();
    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
    startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
    startInfo.FileName = "cmd.exe";
    startInfo.Arguments = "call /c " + localFileName;
    process.StartInfo = startInfo;
    try
    {
        //MessageBox.Show("calling file " + localFileName, "FYI...");
        if (!process.Start())
        {
            MessageBox.Show("Could not invoke the PDF Viewer. Try opening the file at " + localFileName, 
                "Problem Opening File...", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            return;
        }
    }
    catch (Exception exc)
    {
        MessageBox.Show("Couldn't start process (call " + localFileName + "), Message=" + exc.Message, 
        "Problem Encounter...", MessageBoxButtons.OK, MessageBoxIcon.Error);
        return;
    }
    //MessageBox.Show("Should be done", "FYI...");
}

我正在尝试检测进程是否启动。如果我无法让它们执行,如果我可以显示一条消息告诉用户在哪里查看以打开下载的文件,这将有所帮助。有什么想法吗?

【问题讨论】:

    标签: c# pdf


    【解决方案1】:

    您的代码完全错误。绝对不需要cmd.exe 参与此操作,也不需要call /c(并且绝对不需要按照您的回答建议提升)。

    if FileExists(localFileName) {
        try
        { 
          System.Diagnostics.Process.Start(localFileName); 
        catch
        }
          /* 
             Handle failure to start process (Win32Exception)
             No need to handle FileNotFoundException, because
             you can do that in the else below
          */
        };
    }
    else
    {
      // Handle missing file
    }
    

    cmd.exe 不需要,因为它会打开 Windows 命令处理器的新实例(也称为命令提示符),并且仅当 CALL 从批处理文件中输入另一个批处理文件时才需要 call /c。当然没有必要按照您的回答建议提升流程。

    【讨论】:

    • VS 告诉我!System.Diagnostics.Process.Start(localFileName) 出错,运算符 (!) 不能应用于“System.Diagnostic.Process”类型的操作数。
    • 是的,你是对的。我使用的语法是用于不接受任何参数的Start 的重载。已更正。
    • 对,没有参数它返回一个布尔值,有参数它返回一个进程。我刚试过Process.Start(localFileName);,它在XP机器上工作。不过,我也会将其包装在try 中。感谢您的帮助!!!
    【解决方案2】:

    问题似乎与权限有关。我添加了process.Verb = "runas" 以将其提升到管理员级别,并且它可以在 Windows 7 机器上运行。在 XP 机器上,它提示输入管理员密码,这不是很好,但对我的目的来说应该足够了......

    【讨论】:

    • 这是错误的答案(即使您可以接受,但提供给其他人作为解决问题的方法是不正确和错误的信息)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-15
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    • 2010-10-31
    相关资源
    最近更新 更多