CMD command not running in console

2019-06-04 22:34发布

I have some code that runs a cmd command in C# which works really well in a WinForm but when running this in a console app it doesn't work. I am a bit stuck as to why this is, I tried adding Windows.Forms as a reference and added the using to the code but this didn't work either. The only other thing I can think of is that because it is running as a console it can't run another console window on top of this?

Any help is appreciated.

ProcessStartInfo cmd = new ProcessStartInfo("cmd.exe");
cmd.RedirectStandardInput = true;
cmd.RedirectStandardOutput = true;
cmd.RedirectStandardError = true;
cmd.UseShellExecute = false;
cmd.CreateNoWindow = true;
cmd.WindowStyle = ProcessWindowStyle.Hidden;
Process console = Process.Start(cmd);
console.StandardInput.WriteLine("command to run");

标签: c# console cmd
1条回答
迷人小祖宗
2楼-- · 2019-06-04 23:07

The following code will perform any console command you want and output the console text in your current window, everything after while(true) is just as example:

        ProcessStartInfo cmd = new ProcessStartInfo("cmd.exe");
        cmd.RedirectStandardInput = true;
        cmd.UseShellExecute = false;
        cmd.CreateNoWindow = false;
        cmd.WindowStyle = ProcessWindowStyle.Normal;
        Process console = Process.Start(cmd);

        while(true)
            console.StandardInput.WriteLine("pause");

If you don't want any console output then set CreateNoWindow to true. Also this code works inside a console application using System.Diagnostics

Good luck!

查看更多
登录 后发表回答