Run interactive command line exe using c#

前端 未结 3 1414
醉酒成梦
醉酒成梦 2020-12-05 08:17

I can run a command line process using process.start(). I can provide input using standard input. After that when the process demands user input again, how can

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 09:16

    There's an example here that sounds similar to what you need, using Process.StandardInput and a StreamWriter.

            Process sortProcess;
            sortProcess = new Process();
            sortProcess.StartInfo.FileName = "Sort.exe";
    
            // Set UseShellExecute to false for redirection.
            sortProcess.StartInfo.UseShellExecute = false;
    
            // Redirect the standard output of the sort command.  
            // This stream is read asynchronously using an event handler.
            sortProcess.StartInfo.RedirectStandardOutput = true;
            sortOutput = new StringBuilder("");
    
            // Set our event handler to asynchronously read the sort output.
            sortProcess.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler);
    
            // Redirect standard input as well.  This stream
            // is used synchronously.
            sortProcess.StartInfo.RedirectStandardInput = true;
            sortProcess.Start();
    
            // Use a stream writer to synchronously write the sort input.
            StreamWriter sortStreamWriter = sortProcess.StandardInput;
    
            // Start the asynchronous read of the sort output stream.
            sortProcess.BeginOutputReadLine();
            Console.WriteLine("Ready to sort up to 50 lines of text");
            String inputText;
            int numInputLines = 0;
            do 
            {
                Console.WriteLine("Enter a text line (or press the Enter key to stop):");
    
                inputText = Console.ReadLine();
                if (!String.IsNullOrEmpty(inputText))
                {
                    numInputLines ++;
                    sortStreamWriter.WriteLine(inputText);
                }
            }
    

    hope that helps

提交回复
热议问题