0

I'm wondering if there is a way to keep the Command prompt open for multiple inputs, Code:

        private static void openConsole()
        {
            Process p = new Process();
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;

            cmdProc = p;

            cmdProc.Start();
            byte[] dat = Encoding.UTF8.GetBytes("CMD running!");
            stream.Write(dat, 0, dat.Length);
        }
        private static void ConsoleCMDs(string cmd)
        {
            if(cmdProc != null)
            {

                cmdProc.StandardInput.WriteLine(cmd);
                cmdProc.StandardInput.Flush();
                cmdProc.StandardInput.Close(); // i want to remove these so i can just call the ConsoleCMDs method multible times and keep the same console instance, so i can navagate to C:\\ and run commands from there.
                string resp = cmdProc.StandardOutput.ReadToEnd();
                byte[] dat = Encoding.UTF8.GetBytes(resp);
                stream.Write(dat, 0, dat.Length);
            }
            else
            {
                byte[] dat = Encoding.UTF8.GetBytes("CMD not running...");
                stream.Write(dat, 0, dat.Length);
            }
        }

if i remove cmdProc.StandardInput.Close(); then cmdProc.StandardOutput.ReadToEnd() will get stuck, i want to know if theres a way to write to the same command prompt, thanksenter code here

Quinch
  • 141
  • 1
  • 3
  • 3
  • 1
    Instead of using StandardOutput.ReadToEnd, you should use the OutputDataReceived event handler. This will avoid it getting stuck. Just build up the string variable each time the event occurs to produce a similar result. Sample: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.outputdatareceived?view=netframework-4.8 – Wiz Jul 05 '19 at 14:18
  • See the example [here](https://stackoverflow.com/a/51682585/7444103) (about using the Process' events in an *interactive* way). – Jimi Jul 05 '19 at 14:43

0 Answers0