使用Process调用dos命令

本文介绍了如何使用C#通过System.Diagnostics命名空间来运行CMD命令。不仅提供了简单的命令执行示例,还展示了如何通过ProcessStartInfo类配置命令的运行方式,例如隐藏窗口并捕获输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The simplest way to run a command is:

System.Diagnostics.Process.Start ("cmd", @"/c copy c:/myfolder/*.* c:/mybackup");

You can get creative using System.Diagnostics.ProcessStartInfo... for instance you can have your command run without showing a window and capturing the output of the command to process it as you prefer (for instance, displaying it in your console). A simple example of this follows:

// create the ProcessStartInfo using "cmd" as the program to be run, and "/c dir" as the parameters.
// Incidentally, /c tells cmd that we want it to execute the command that follows, and then exit.
// To have more information, start cmd and type help cmd.
System.Diagnostics.ProcessStartInfo sinf =

new System.Diagnostics.ProcessStartInfo ("cmd", "/c dir");
// The following commands are needed to redirect the standard output. This means that it will be redirected to the Process.StandardOutput StreamReader.
sinf.RedirectStandardOutput =
true;
sinf.UseShellExecute =
false;
// Do not create that ugly black window, please...
sinf.CreateNoWindow =
true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process p =
new System.Diagnostics.Process ();
p.StartInfo = sinf;
p.Start (); // well, we should check the return value here...
// We can now capture the output into a string...

string res = p.StandardOutput.ReadToEnd ();
// And do whatever we want with that.
Console.WriteLine (res);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值