I'm opening an external application from a console application, as follows:
var p = new Process
{
StartInfo =
{
FileName = "SomeApp.exe"
}
};
p.Start();
Thread.Sleep(10000);
p.CloseMainWindow(); //Bam!! InvalidOperationExcetion
How can I close SomeApp.exe? I'm building some automation around this application and I would like it do be closed whenever I'm done with it, but I haven't been successful so far.
p.CloseMainWindow()
throws an exception of type InvalidOperationException with message "Cannot process request because the process (1216) has exited."
I'm not killing the process and I don't know what is killing it. I'm running this console application from Visual Studio in Administrator mode.
Any ideas? Thanks you in advance
When you call .WaitForExit()
your current process waits until the external application is closed. There is no point in calling .Kill()
afterwards, because the process is already gone. A simple example:
var p = new Process
{
StartInfo =
{
FileName = "cmd.exe"
}
};
p.Start();
Console.WriteLine("press any key to kill the other app");
Console.ReadKey();
if (!p.HasExited)
{
p.Kill();
Console.WriteLine("other app was killed");
}
else
{
Console.WriteLine("other app was already dead");
}
Console.ReadKey();
Depending on what you want, you may as well just skip the call to .Kill()
in your current code - as I've mentioned, the external process is already gone after .WaitForExit()
.