locked
FAQs:如何重定向标准I/O? RRS feed

答案

  • 更多细节的介绍,请参阅Manish Ranjan Kumar的文章:
    http://www.codeproject.com/KB/cs/ProcessStartDemo.aspx

    这是代码示例:
            static void Main(string[] args)
            {
                StreamReader outputReader = null;
                StreamReader errorReader = null;

                try
                {
                    ProcessStartInfo psi = new  ProcessStartInfo(@"c:\Program.exe", "a b c");

                    psi.ErrorDialog = false;
                    psi.UseShellExecute = false;
                    psi.RedirectStandardError = true;
                    psi.RedirectStandardInput = true;
                    psi.RedirectStandardOutput = true;

                    Process proc = new Process();
                    proc.StartInfo = psi;
                    bool started = proc.Start();
                    if (started)
                    {
                        outputReader = proc.StandardOutput;
                        errorReader = proc.StandardError;
                        proc.WaitForExit();

                        string displayText = "Output" + Environment.NewLine;
                        displayText += outputReader.ReadToEnd();
                        displayText += Environment.NewLine + "Error" + Environment.NewLine;
                        displayText += errorReader.ReadToEnd();

                        Console.WriteLine(displayText);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
                finally
                {
                    if(outputReader != null)
                    {
                        outputReader.Close();
                    }
                    if(errorReader != null)
                    {
                        errorReader.Close();
                    }
                }
            }

    假设应用程序A需要一个接一个的输入一些参数。为了在应用程序B中调用应用程序A,我们需要重定向标准输入。
    这是应用程序A的示例:
    static void Main(string[] args)
            {
                string input1 = Console.ReadLine();
                string input2 = Console.ReadLine();

                Console.WriteLine(input1);
                Console.WriteLine(input2); 
            }
    这是应用程序B的代码:
    static void Main(string[] args)
            {
                ProcessStartInfo psi = new ProcessStartInfo();
                psi.FileName = @"c:\applicationA.exe";
                psi.UseShellExecute = false;
                psi.RedirectStandardInput = true;
                Process proc = new Process();
                proc.StartInfo = psi;
                proc.Start();

                proc.StandardInput.WriteLine(10);
                proc.StandardInput.WriteLine(20);
            }


    如果您对我们的论坛在线支持服务有任何的意见或建议,请通过邮件告诉我们。
    MSDN 论坛好帮手 立刻免费下载  MSDN 论坛好帮手
    2011年3月2日 10:49