Friday, October 10, 2008

Output Redirection in C#

Sometimes, it will be necessary to redirect the output of a command to a variable or a control. This is very useful when we are working with DOS commands, which display data in the console that can be used by the application. For example, if you want to process the output of a command such as TASKLIST or some other third party command which lists useful information (which does not have any programming interface), this technique is useful.

What we need to do is to redirect the input, output and error streams to our stream variables and use them for putting data and reading results. Below code snippet demonstrates this concept:

using System.IO;
using System.Diagnostics;

private void RedirectOutput(string command,
                            out string outputMessage,
                            out string errorMessage)
{
    using (Process proc = new Process())
    {
        ProcessStartInfo psI = new ProcessStartInfo("CMD.EXE");

        psI.UseShellExecute = false;

        // Choose the streams to be redirected
        psI.RedirectStandardInput = true;
        psI.RedirectStandardOutput = true;
        psI.RedirectStandardError = true;

        // Do not create a new window
        psI.CreateNoWindow = true;

        proc.StartInfo = psI;
        proc.Start();

        // Create writer/reader objects for redirection
        using (StreamWriter writer = proc.StandardInput)
        {
            using (StreamReader reader = proc.StandardOutput)
            {
                using (StreamReader errorReader = proc.StandardError)
                {
                    writer.AutoFlush = true;

                    // Write the command
                    writer.WriteLine(command);
                    writer.Close();

                    // Get output & error messages
                    outputMessage = reader.ReadToEnd();
                    errorMessage = errorReader.ReadToEnd();
                }
            }
        }
    }
}

By following this method, it is very easy to develop applications with functionality similar to TELNET. The above code can be modified easily to make the session interactive.

No comments: