简体   繁体   中英

how to execute a command prompt command in my own console application

如何使控制台应用程序窗口的行为类似于命令提示符窗口并执行命令行参数?

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM