2

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Vilx-
  • 104,512
  • 87
  • 279
  • 422

4 Answers4

2

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.

Brigand
  • 84,529
  • 20
  • 165
  • 173
  • That's what you get when trying to use the command line of one program after having studied the command line of another program right before that (TortoiseSVN in my case). :P – Vilx- Jan 12 '12 at 15:51
1

You could place your commands in a batch (.bat) file, and make the last command within the batch file "pause" (without quotes). Then, instead of executing cmd, execute the batch file instead.

Sample batch file - test.bat

dir pause

You could also output the results to a text file, then show the text file within your application.

DIR >results.txt
John Easley
  • 1,551
  • 1
  • 13
  • 23
  • Plausible, but there are many such scripts and I don't want to write a separate .BAT file for each of them. I _could_ generate a temporary .BAT file on the fly... but that seems like a hacky workaround. Isn't there a better way? – Vilx- Jan 12 '12 at 14:00
  • You could output the results to a file, then open and display the file. C:> DIR > dirResults.txt – John Easley Jan 12 '12 at 17:50
1

Remove the colon from your example:

System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo()
{
  Arguments = "/K dir",
  ErrorDialog = true,
  FileName = "cmd.exe",
  WorkingDirectory = @"C:\"
});
devdigital
  • 34,151
  • 9
  • 98
  • 120
0

I would log errors to a file rather than keep the window open. to keep the .net console window open add

Console.ReadLine();

to the end, this will require the user to press Enter to continue. you can also use Console.ReadKey() to use any key

if you want to keep the Process windows open the command is pause

Jason Meckley
  • 7,589
  • 1
  • 24
  • 45