1

I had a piece of code to display the properties window of a file,

ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = @"C:\Users\nyongrand\Desktop\Internet Download Manager.lnk";
psi.Verb = "properties";
Process process = Process.Start(psi);
process.WaitForExit(); //This give me exception, Object reference not set to an instance of an object.

what I want is to wait until the window properties is closed, because if my code closed the properties window will be closed as well, I need a solution between, my code is able to wait for the properties window closed, or my code can exit without closing the properties window.

4

2 回答 2

1

The exception you're getting means that process is null at the time you try to call its WaitForExit member method. So the question you should be asking is why.

Start with the documentation for the overload of the Process.Start function that you're calling to see what it actually returns. Sure enough, it returns a Process object, but only under certain conditions:

Return Value
Type: System.Diagnostics.Process
A new Process component that is associated with the process resource, or null if no process resource is started (for example, if an existing process is reused).

And, from the "Remarks" section:

Note: If the address of the executable file to start is a URL, the process is not started and null is returned.

So, if an existing process is re-used, the Process.Start method will return null. And you cannot call methods on null.

于 2013-05-07T23:55:26.647 回答
0

Try replacing

Process process = Process.Start(psi);

with

Process process = new Process();

if(process.Start(psi))
{
    process.WaitForExit();
}
else
{
    //Do something here to handle your process failing to start
}

The problem you face with your code is that Process.Start() returns a Boolean. It's not a factory for Process objects.

于 2013-05-07T23:53:01.480 回答