C#调用cmd已经详细写了调用的方法,接下来具体介绍一个例子:
通过C# 调用cmd clone和拉取git的代码和生成日志
第一步:配置git ,要有权限拉取代码
第二部:调用cmd
public void RunCloneCmd(string path, string command)
{
Process pro = new Process();
//Pro = pro;
pro.StartInfo.FileName = "cmd.exe";
pro.StartInfo.CreateNoWindow = true; // 不创建新窗口
pro.StartInfo.UseShellExecute = false; //不启用shell启动进程
pro.StartInfo.RedirectStandardInput = true; // 重定向输入
pro.StartInfo.RedirectStandardOutput = true; // 重定向标准输出
pro.StartInfo.RedirectStandardError = false; //重定向标准错误
// 重定向错误输出
pro.StartInfo.WorkingDirectory = path; //定义执行的路径
pro.Start();
pro.StandardInput.WriteLine(command); //向cmd中输入命令
pro.StandardInput.AutoFlush = true;
pro.StandardInput.WriteLine("exit"); //退出
string outRead = pro.StandardOutput.ReadToEnd(); //获得所有标准输出流
pro.WaitForExit(); //等待命令执行完成后退出
pro.Close(); //关闭窗口
}
定义执行的路径:
在cmd中==在E:\webNet路径下执行
如:
E:\webNet>git --version
如何获得标准输出流和错误流有两种方式
按照行读取
StreamReader reader = p.StandardOutput;//获取cmd输出流
string line = reader.ReadLine();//每次读取一行
while (!reader.EndOfStream)
{
line = reader.ReadLine();
}
一起读:
string outRead = pro.StandardOutput.ReadToEnd();
输出的内容如下:
错误流也一样:
string outRead = pro.StandardError.ReadToEnd();
如果没有安装git在cmd拉取代码正常,通过C#调用CMD却没有输出,需要重启电脑让Git生效:否则报如下错误:(截取一部分错误)
获取git日志:
执行 string commont = @”git log –name-status –date=format:”“%Y-%m-%d %H:%M:%S”” –pretty=format:”“#%H# %cn# %ce# %cd# %s#”“> log.txt”;
命令即可获得git日志log.txt文件