Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

c# - Repeatably Feeding Input to a Process' Standard Input

I have a (C#) console application which maintains a state. The state can be altered by feeding the application with various input through the console. I need to be able to both feed the application with a bit of input, then read the output rinse and repeat.

I create a new process and do all of the normal work of redirecting the input/output. The problem is that after I've sent input and call ReadLine() on the standard output it does not return a value before I call Close() on the standard input after which I cannot write anymore to the input stream.

How can I keep open the input stream while still receiving output?

 var process = new Process
                          {
                              StartInfo =
                                  {
                                      FileName =
                                          @"blabal.exe",
                                      RedirectStandardInput = true,
                                      RedirectStandardError = true,
                                      RedirectStandardOutput = true,
                                      UseShellExecute = false,
                                      CreateNoWindow = true,
                                      ErrorDialog = false
                                  }
                          };


        process.EnableRaisingEvents = false;

        process.Start();

        var standardInput = process.StandardInput;
        standardInput.AutoFlush = true;
        var standardOutput = process.StandardOutput;
        var standardError = process.StandardError;

        standardInput.Write("ready");
        standardInput.Close(); // <-- output doesn't arrive before after this line
        var outputData = standardOutput.ReadLine();

        process.Close();
        process.Dispose();

The console application I'm redirecting IO from is very simple. It reads from the console using Console.Read() and writes to it using Console.Write(). I know for certain that this data is readable, since I have another application that reads from it using standard output / input (not written in .NET).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That is happening because of you are using Write("ready") which is will append a string to the text, instead use WriteLine("ready"). that simple :).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...