Using cmd.exe from C#

2019-06-09 15:11发布

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

2条回答
Melony?
2楼-- · 2019-06-09 15:52

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

查看更多
看我几分像从前
3楼-- · 2019-06-09 15:55

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.

查看更多
登录 后发表回答