重定向命令行输出,包括用户输入C#的文本提示

时间:2015-04-25 12:53:10

标签: c# process console command

很多天我在谷歌上搜索这个问题,但没有找到任何答案。 我有这样的批处理文件。

@ECHO OFF
ECHO This is sample output.
SET /P uname=Please enter your name: 
IF "%uname%"=="" GOTO Error
ECHO Hello %uname%, Welcome to DOS inputs!
GOTO End
:Error
ECHO You did not enter your name! Bye bye!!
:End
pause

我们如何从这个命令中看到,它将打印"这是样本输出。"行然后会询问用户的名字。在C#"这是示例输出。"将收到该行作为输出数据,但文本"请输入您的姓名:"我们只在控制台输入一些东西后收到。 那么,我们如何在输入内容之前接收提示输出,我们可以重定向完整控制台吗? (如果我们可以这么说)。 以下是测试应用程序。

using System;
using System.Diagnostics;

namespace CommandExecuter
{
    static class Program
    {
        static void Main()
        {
            try
            {
                var start = new ProcessStartInfo
                {
                    FileName = @"C:\run.cmd",
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true
                };

                using (var process = new Process())
                {
                    process.StartInfo = start;
                    process.OutputDataReceived += process_OutputDataReceived;
                    process.ErrorDataReceived += process_ErrorDataReceived;

                    process.Start();

                    process.BeginOutputReadLine();
                    process.BeginErrorReadLine();

                    process.WaitForExit();

                    process.CancelOutputRead();
                    process.CancelErrorRead();
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to execute command: " + ex.Message);
            }
            finally
            {
                Console.ReadLine();
            }
        }

        private static void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (!string.IsNullOrEmpty(e.Data))
            {
                Console.Write("OutputDataReceived: " + e.Data + Environment.NewLine);
            }
        }

        private static void process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (!string.IsNullOrEmpty(e.Data))
            {
                Console.Write("ErrorDataReceived: " + e.Data + Environment.NewLine);   
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

将你的if改变一段时间。我认为你得到了多条回程线



      private static void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            while (!string.IsNullOrEmpty(e.Data))
            {
                Console.Write("OutputDataReceived: " + e.Data + Environment.NewLine);
            }
        }

​