Search code examples
.netconsoleprocessstartinfo

How to start a console application and prevent it from closing at the end?


I'm starting a shell script (.cmd) from my .NET application. I'd like the console window to remain open after the script has completed so that I can check for any errors. I'm trying with cmd.exe /K:my.cmd, but for some reason that does not work (the script does not get executed). Even a simple "dir" command does not work. Any other ideas?

To demonstrate, this:

System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo()
{
    Arguments = "/K:dir",
    ErrorDialog = true,
    FileName = "cmd.exe",
    WorkingDirectory = @"C:\"
});

Gives me this:

C:\>

Added clarification: My application (the one that starts the script) is a windows forms application. Executing the above code opens a new console window (as it should). I want THAT new console window to remain open. Also, I cannot modify the script. It's an automated build script and it HAS to terminate.


Solution

  • I don't know if this is the whole problem, but if you run cmd /K:dir, nothing is run. Using a space instead of a colon makes it work for me.

    i.e., cmd /K dir


    It's also worth noting that you can test these commands in the run dialog. In any recent Windows version this can be done by holding down Win and pressing R.