C#执行CMD命令

来源:互联网 发布:mac相册导入移动硬盘 编辑:程序博客网 时间:2024/05/17 07:42

摘自《31天学会CRM项目开发<C#编程入门级项目实战>》

Windows操作系统命令提示符中可通过执行dos命令实现大部分系统级操作。如图5-3所示,在本示例中通过C#代码调用cmd.exe程序并执行dos指令。例如ping命令,或shutdown –s -t 1关机指令。


片段5-37演示了在C#中启动一个进程,执行cmd命令,并取得命令执行结果。

 代码片段5-37

private string RunCmd(string command){    // 需用引用命名空间System.Diagnostics;    // 打开一个新进程    Process p = new Process();    // 指定进程程序名称    p.StartInfo.FileName = "cmd.exe";    // 设定要输入命令    p.StartInfo.Arguments = "/c " + command;    // 关闭Shell的使用    p.StartInfo.UseShellExecute = false;    // 重定向标准输入    p.StartInfo.RedirectStandardInput = true;    // 重定向标准输出    p.StartInfo.RedirectStandardOutput = true;    // 重定向错误输出    p.StartInfo.RedirectStandardError = true;    // 不显示命令提示符窗口    p.StartInfo.CreateNoWindow = true;    // 启动程序    p.Start();    // 返回执行的结果    return p.StandardOutput.ReadToEnd();       }


0 0