Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect Standard Output Efficiently in .NET

Tags:

c#

.net

process

cgi

I am trying to call php-cgi.exe from a .NET program. I use RedirectStandardOutput to get the output back as a stream but the whole thing is very slow.

Do you have any idea on how I can make that faster? Any other technique?

    Dim oCGI As ProcessStartInfo = New ProcessStartInfo()
    oCGI.WorkingDirectory = "C:\Program Files\Application\php"
    oCGI.FileName = "php-cgi.exe"
    oCGI.RedirectStandardOutput = True
    oCGI.RedirectStandardInput = True
    oCGI.UseShellExecute = False
    oCGI.CreateNoWindow = True

    Dim oProcess As Process = New Process()

    oProcess.StartInfo = oCGI
    oProcess.Start()

    oProcess.StandardOutput.ReadToEnd()
like image 366
Vincent Avatar asked Oct 02 '08 21:10

Vincent


2 Answers

The best solution I have found is:

private void Redirect(StreamReader input, TextBox output)
{
    new Thread(a =>
    {
        var buffer = new char[1];
        while (input.Read(buffer, 0, 1) > 0)
        {
            output.Dispatcher.Invoke(new Action(delegate
            {
                output.Text += new string(buffer);
            }));
        };
    }).Start();
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    process = new Process
    {
        StartInfo = new ProcessStartInfo
        {
            CreateNoWindow = true,
            FileName = "php-cgi.exe",
            RedirectStandardOutput = true,
            UseShellExecute = false,
            WorkingDirectory = @"C:\Program Files\Application\php",
        }
    };
    if (process.Start())
    {
        Redirect(process.StandardOutput, textBox1);
    }
}
like image 92
Jader Dias Avatar answered Oct 02 '22 16:10

Jader Dias


You can use the OutputDataReceived event to receive data as it's pumped to StdOut.

like image 33
Bob King Avatar answered Oct 02 '22 16:10

Bob King