0

I'm looking into writing a sort of command prompt wrapper as a learning exercise. Basically the user enters a command in the console window and the command is executed via cmd.exe.

"Run Command Prompt Commands" handles the execution of the commands via cmd.exe, while "Process.start: how to get the output?" takes care of obtaining the resulting output.

There is one problem I have yet to address. This method of executing commands via cmd.exe causes a process to start, do whatever it has to do, and then terminate. So if I do something like cd.., the expected change in state does not persist between subsequent commands, and you'll see that you remain in the same working directory.

Is it possible to execute shell commands while maintaining a persistent cmd.exe session?

Community
  • 1
  • 1
Gigi
  • 28,163
  • 29
  • 106
  • 188
  • I think your confusion comes from the fact that there are external commands that cmd.exe can launch, but there are also internal commands that cmd.exe interprets without passing them on to Windows. Commands like `cd` and `set`. You should be processing those internally. – itsme86 Dec 14 '14 at 21:45
  • @itsme86 Yes, exactly - how is that done? – Gigi Dec 14 '14 at 21:50
  • Reference @MartinLiversage's answer. – itsme86 Dec 14 '14 at 21:51

2 Answers2

2

Don't use /c to run the commands at all. Leave cmd.exe open the whole time, and redirect its stdin the same way you redirect stdout, then feed it commands as needed.

var proc = new Process {
    StartInfo = new ProcessStartInfo {
        FileName = "cmd.exe",
        UseShellExecute = false,
        RedirectStandardError = true,
        RedirectStandardOutput = true,
        RedirectStandardInput = true,
        CreateNoWindow = true
    }
};

proc.StdIn.WriteLine("cd ..");
// other commands from the user

As a bonus, this handles all kinds of statefulness in the spawned process; things like %ERRORCODE%, setting variables, changing the prompt, and even running nested interpreters.

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
0

Every process in Windows including shells like CMD.EXE has a current directory. You can change the current directory in .NET using Directory.SetCurrentDirectory. Executing cd .. in a command prompt does not start a new cd process. Instead the CMD.EXE processes the cd command directly and changes the current directory of the command processor using the Windows API. You will have to do something similar in your command processor.

Martin Liversage
  • 104,481
  • 22
  • 209
  • 256