简体   繁体   中英

C# Problems with Reading Standard Output

This ones got me stumped. So I'm making a program in C# to provide a GUI frontend for the Terraria Server. I have tried several methods but I always get the same problem. First I start the process using System.Diagnostic. Then I have tried several things, such as asynchronously reading the console output using BeginOutputReadLine or creating a Background worker to execute the following:

        while (!terrariaProcess.StandardOutput.EndOfStream)
        {
            consoleOutput.Items.Add(terrariaProcess.StandardOutput.ReadLine());
        }

But the output always comes out muddled. Example It should be: (How it looks if I use cmd to execute it)

Terraria Server v1.0.6.1
Choose World: 
1       Test
n       New World
d <number>  Delete World
>>n
Choose size:
1       Small
2       Medium
3       Large
>>3
Enter World Name:
>>Hello World

However my program reads it as:

Terraria Server v1.0.6.1
1       Test
n       New World
d <number>  Delete World
>>n
Choose World: Terraria Server v1.0.6.1
1       Small
2       Medium
3       Large
>>3
Choose size: Terraria Server v1.0.6.1
>>Hello World

It does this no matter what method I use. Can someone help please? Am I being an idiot (again)?

EDIT: On Jon's request I have made a small console application to try to do the same thing. I am having some trouble checking for console input from within a loop so I can only test up to the first prompt but it still seems broken. My code:

    Process terrariaProcess;
    terrariaProcess = new Process();
    terrariaProcess.StartInfo.FileName = "TerrariaServer.exe";
    terrariaProcess.StartInfo.UseShellExecute = false;
    terrariaProcess.StartInfo.RedirectStandardInput = true;
    terrariaProcess.StartInfo.RedirectStandardOutput = true;
    terrariaProcess.StartInfo.CreateNoWindow = true;
    terrariaProcess.Start();
    while (!terrariaProcess.StandardOutput.EndOfStream)
    {
        Console.WriteLine(terrariaProcess.StandardOutput.ReadLine());
    }

The result output:

Terraria Server v1.0.6.1
1       Test
n       New World
d <number>  Delete World

调用函数Console.Out.Flush();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM