0

I'm building a small Console Application that sometimes will use the Windows Command Line, to send a command and then receive and display the output.

Opening a new Command Line instance was easy, sending commands from my Application took a bit of digging but its working. However i can't seem to be able to read the output from the Command Line.

My code is based on:

How to redirect Standard Input/Output of an application

How do I run Command line commands from code

I applied the same way of reading the output to my application, and it doesn't work, not until the moment i close my application, while is being shutdown I'm able to have a glimpse at the output.

Its working, but most likely i have misplaced code, that prevents me to see the output, until i start to shutdown my application.

Can somebody help me with this?

Code:

        Process p = new Process();
        p.StartInfo.FileName = Environment.GetEnvironmentVariable("comspec");
        p.StartInfo.ErrorDialog = false;
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardError = true;
        p.StartInfo.RedirectStandardInput = true;
        p.StartInfo.RedirectStandardOutput = true;

        //Execute the process
        if (p.Start())
        {
            //Get the output stream
            StreamReader outputReader = p.StandardOutput;
            StreamReader errorReader = p.StandardError;

            // Assign a Stream Writer to send the Commands
            StreamWriter commandWriter = p.StandardInput;

            // Send the "Dir" command to the command line instance.
            commandWriter.Write("dir");
            commandWriter.Write(commandWriter.NewLine);

            p.WaitForExit();

            //Display the result
            Console.WriteLine(outputReader.ReadToEnd());

            outputReader.Close();
            errorReader.Close();
            commandWriter.Close();
        }

1 Answer 1

4

The problem is that you're not telling cmd.exe to exit. Simply send "exit\r\n" when done.

Another problem you will eventually run into is that you need to read stdout and stdin asyncronously.

using System;
using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        Process p = new Process();
        p.StartInfo.FileName = Environment.GetEnvironmentVariable("comspec");
        p.StartInfo.ErrorDialog = false;
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardError = true;
        p.StartInfo.RedirectStandardInput = true;
        p.StartInfo.RedirectStandardOutput = true;
        // Hook up async stdout and stderr reading
        p.ErrorDataReceived += ConsoleDataReceived;
        p.OutputDataReceived += ConsoleDataReceived;

        // Execute the process
        if (p.Start())
        {
            // Begin async stdout and stderr reading
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();

            // Send the "Dir" command to the command line instance.
            p.StandardInput.WriteLine("dir");

            // Send "exit" and wait for exit
            p.StandardInput.WriteLine("exit");
            p.WaitForExit();
        } 
    }

    static void ConsoleDataReceived(object sender, DataReceivedEventArgs e)
    {
        if (e.Data != null)
            Console.WriteLine(e.Data);
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Of course, i totally forgot it. Thanks for the heads up as well.
What is "ConsoleDataReceived"?
@TMarshall: Keep reading. There are two methods defined in that code: Main and ConsoleDataReceived.
OH MAN do I feel stupid! I didn't notice the scroll bar. Should have gotten some sleep last night. Thanks for setting me straight!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.