WaitForExit() throws exception c#

.net, c#

Solution

Because when you start a process indirectly you won't get `Process` object (then in your case process is always `null` and second line throws an exception).

Let me explain what I mean with indirectly: if you don't specify an executable but you give a document (or a resource) then it'll be executed through a shell verb. In this case an existing process may be (re)used. In this cases `Process.Start()` will return `null`.

Try this:

- Create an empty Word document 'c:\test.docx'.

- Close all Word instances.

- Execute `Process.Start(@"c:\test.docx"); // Returns a Process instance`

- Execute `Process.Start(@"c:\test.docx"); // Returns null`

Can you simply solve this? AFAIK you can't because `Process` uses `ShellExecuteEx` with a SHELLEXECUTEINFO structure to start the process. Reading `SHELLEXECUTEINFO` documentation for `hProcess` field you'll see that:

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.

Note if you're running a new process just to open an URL and get a server side generated file then you should follow Damien's suggestion and use a `WebClient.DownloadFile()`.

Problem

Below is my code to start the process, have put link for demo only.I want this process to run in background without opening browser. Also 2nd line throws exception Object reference not set to an instance of an object. ``` var process=Process.Start("http://www.google.com"); process.WaitForExit(); ```

Original source