Run interactive command line exe using c#

早过忘川 提交于 2019-11-27 19:52:55

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

If I understand correctly I think you should be able to do this by redirecting the Standard Input/Output using RedirectStandardOutput and RedirectStandardInput.

The WinSCP project has a C# sample for how to communicate with it using this way. You can find it here: SFTP file transfers in .NET (though this sample only collects the output without using it at all, but the technique should be the same.)

You want to look up IPC. As robert showed above, the Process class in .NET will help you. But specifically for your problem (how to know when to write data): You can't. Not generically.

If you know the required input (e.g. "yyy"), you can supply it in the STDIN of the created process. You don't have to wait for the program to request this information: It will just read from STDIN when it wants data.

If you need to process the programs output to decide what to write to STDIN, try reading the processes STDOUT. You might run into problems with flushing, though...

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!