Question

how can i make my console application window to behave like a command prompt window and execute my command line arguments?

Was it helpful?

Solution

This should get you started:

public class Program
{
    public static void Main(string[] args)
    {
        var proc = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName               = "cmd.exe",
                CreateNoWindow         = true,
                UseShellExecute        = false,
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                RedirectStandardError  = true
            }
        };

        proc.Start();

        new Thread(() => ReadOutputThread(proc.StandardOutput)).Start();
        new Thread(() => ReadOutputThread(proc.StandardError)).Start();

        while (true)
        {
            Console.Write(">> ");
            var line = Console.ReadLine();
            proc.StandardInput.WriteLine(line);
        }
    }

    private static void ReadOutputThread(StreamReader streamReader)
    {
        while (true)
        {
            var line = streamReader.ReadLine();
            Console.WriteLine(line);
        }
    }
}

The basics are:

  • open cmd.exe process and capture all three streams (in, out, err)
  • pass input from outside in
  • read output and transfer to your own output.

The "Redirect" options are important - otherwise you can't use the process' respective streams.

The code above is very basic, but you can improve on it.

OTHER TIPS

I believe you are looking for this

var command = "dir";
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
string result = proc.StandardOutput.ReadToEnd();
Console.WriteLine(result);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top