c# - WaitForExit() 抛出异常 c#

标签 c# .net

下面是我启动该过程的代码,只放了演示链接。我希望这个过程在不打开浏览器的情况下在后台运行。第二行也抛出异常

Object reference not set to an instance of an object.

var process=Process.Start("http://www.google.com");
process.WaitForExit();

最佳答案

因为当你间接启动一个进程时,你不会得到Process对象(那么在你的情况下进程总是null和第二行抛出异常)。

让我解释一下我的意思是间接:如果您没有指定可执行文件但您提供了文档(或资源),那么它将执行通过 shell 动词。在这种情况下,可以(重新)使用现有流程。在这种情况下,Process.Start() 将返回 null

试试这个:

  • 创建一个空的 Word 文档“c:\test.docx”。
  • 关闭所有 Word 实例。
  • 执行 Process.Start(@"c:\test.docx");//返回一个流程实例
  • 执行 Process.Start(@"c:\test.docx");//返回空值

你能简单地解决这个问题吗?据我所知你不能因为 Process 使用 ShellExecuteExSHELLEXECUTEINFO结构来启动进程。阅读 SHELLEXECUTEINFO 文档的 hProcess 字段你会看到:

A handle to the newly started application. This member is set on return and is always NULL unless fMask is set to SEE_MASK_NOCLOSEPROCESS. Even if fMask is set to SEE_MASK_NOCLOSEPROCESS, hProcess will be NULL if no process was launched. For example, if a document to be launched is a URL and an instance of Internet Explorer is already running, it will display the document. No new process is launched, and hProcess will be NULL. Note ShellExecuteEx does not always return an hProcess, even if a process is launched as the result of the call. For example, an hProcess does not return when you use SEE_MASK_INVOKEIDLIST to invoke IContextMenu.

注意 如果您正在运行一个新进程只是为了打开一个 URL 并获取服务器端生成的文件,那么您应该遵循 Damien's suggestion并使用 WebClient.DownloadFile()

关于c# - WaitForExit() 抛出异常 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20701716/

相关文章:

c# - 无论如何,这个 LINQ 最终会做太多工作吗?

C# 在不窃取焦点的情况下启动应用程序进程

c# - UWP MVVM Observablecollection 已更新但未反射(reflect)在 UI 上

c# - 获取数组的尾部

c# - Entity Framework 6 DBContext 只有所有表的一个子集

.net - 我可以将节点文本包装在WinForms TreeView中吗

c# - 考虑到夏令时,如何添加时间

c# - 识别 TPL 数据流中的同时任务

.net - 比较 .NET 中两种方法实现之间的性能

c# - .NET Image.Save 偶尔会生成带有错误 IDAT block 的 PNG