Using cmd.exe from C#

2019-06-09 15:53发布

问题:

I have been toying with the Process class in C#. I have some code below I'd like to use to open cmd.exe and run the DIR command. However, when I attempt to use the code, the cmd.exe opens, but no command is run. Why is this happening and how do I fix it?

Process cmd = new Process();
cmd.StartInfo.FileName = @"cmd.exe";
cmd.StartInfo.Arguments = @"DIR";
cmd.Start();
cmd.WaitForExit();

回答1:

Try passing the /K option to let the command console stay at video and receive the subsequent DIR command (Without exit).

Process cmd = new Process();
cmd.StartInfo.FileName = @"cmd.exe";
cmd.StartInfo.Arguments = @"/K DIR";  // <-- This will execute the command and wait to close
cmd.Start();
cmd.WaitForExit();

The /K option will allow you to get a better understanding of what happens in the command window because the window will not close immediately and you need to click the close button or type the Exit command. If you want to exit after issuing your commands then use the /C option.



回答2:

cmd.StartInfo.Arguments = @"/c DIR";