码迷,mamicode.com
首页 > Windows程序 > 详细

[C#] C#代码执行cmd命令

时间:2019-05-07 10:23:18      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:lex   cut   控制台   图片   static   amp   窗口   opened   exec   

引入命名空间

using System.Diagnostics;

 


 

具体方法实现

技术图片
 1 class Cmd
 2 {
 3     private static string CmdPath = @"C:\Windows\System32\cmd.exe";
 4     /// <summary>
 5     /// 执行cmd命令 返回cmd窗口显示的信息
 6     /// 多命令请使用批处理命令连接符:
 7     /// <![CDATA[
 8     /// &:同时执行两个命令
 9     /// |:将上一个命令的输出,作为下一个命令的输入
10     /// &&:当&&前的命令成功时,才执行&&后的命令
11     /// ||:当||前的命令失败时,才执行||后的命令]]>
12     /// </summary>
13     /// <param name="cmd">执行的命令</param>
14     public static string RunCmd(string cmd)
15     {
16         cmd = cmd.Trim().TrimEnd(&) + "&exit";//说明:不管命令是否成功均执行exit命令,否则当调用ReadToEnd()方法时,会处于假死状态
17         using (Process p = new Process())
18         {
19             p.StartInfo.FileName = CmdPath;
20             p.StartInfo.UseShellExecute = false;        //是否使用操作系统shell启动
21             p.StartInfo.RedirectStandardInput = true;   //接受来自调用程序的输入信息
22             p.StartInfo.RedirectStandardOutput = true;  //由调用程序获取输出信息
23             p.StartInfo.RedirectStandardError = true;   //重定向标准错误输出
24             p.StartInfo.CreateNoWindow = true;          //不显示程序窗口
25             p.Start();//启动程序
26 
27             //向cmd窗口写入命令
28             p.StandardInput.WriteLine(cmd);
29             p.StandardInput.AutoFlush = true;
30 
31             //获取cmd窗口的输出信息
32             string output = p.StandardOutput.ReadToEnd();
33             p.WaitForExit();//等待程序执行完退出进程
34             p.Close();
35 
36             return output;
37             }
38         }
39     }
Code

 


 

方法的使用

string put = Cmd.RunCmd("命令");    //执行命令
Console.WriteLine(put);        //控制台输出返回结果

 

[C#] C#代码执行cmd命令

标签:lex   cut   控制台   图片   static   amp   窗口   opened   exec   

原文地址:https://www.cnblogs.com/lang-lang/p/10823783.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!