CSharp 调用控制台程序传入命令并执行

CSharp 调用命令行实例

在使用C#调用命令行程序时因为需要输入命令行要执行的命令所以经过很多尝试得到一些结果。

1. 调用CMD

实例1:在调用CMD的命令时可以通过对输入流进行重定向的设置,然后进行不断的输入。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/// <summary>
/// 执行cmd命令 输出计算机内核及其他信息
/// </summary>
public static void CreateDll()
{

Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
//是否使用操作系统shell启动
p.StartInfo.UseShellExecute = false;
//重定向输入流,接受来自调用程序的输入信息
p.StartInfo.RedirectStandardInput = true;
//由调用程序获取输出信息
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = false;
p.Start();
/*写入要实行的命令此处是可以使用循环不断的写入和或去输入的*/
p.StandardInput.WriteLine("systeminfo");
Console.Write(p.StandardOutput.ReadToEnd());
p.StandardInput.WriteLine("exit");
}


/// <summary>
/// 执行Cmd命令
/// </summary>
public static void RunCmd()
{

string str = Console.ReadLine();

System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动
p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
p.StartInfo.CreateNoWindow = true;//不显示程序窗口
p.Start();//启动程序

//向cmd窗口发送输入信息
p.StandardInput.WriteLine(str + "&exit");

p.StandardInput.AutoFlush = true;
//p.StandardInput.WriteLine("exit");
//向标准输入写入要执行的命令。这里使用&是批处理命令的符号,表示前面一个命令不管是否执行成功都执行后面(exit)命令,如果不执行exit命令,后面调用ReadToEnd()方法会假死
//同类的符号还有&&和||前者表示必须前一个命令执行成功才会执行后面的命令,后者表示必须前一个命令执行失败才会执行后面的命令

//获取cmd窗口的输出信息
string output = p.StandardOutput.ReadToEnd();

//StreamReader reader = p.StandardOutput;
//string line=reader.ReadLine();
//while (!reader.EndOfStream)
//{
// str += line + " ";
// line = reader.ReadLine();
//}

p.WaitForExit();//等待程序执行完退出进程
p.Close();

Console.WriteLine(output);
}

实例2:此外还可以通过传入参数的方式调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/// <summary>  
/// 执行DOS命令,返回DOS命令的输出
/// </summary>
/// <param name="dosCommand">dos命令</param>
/// <param name="milliseconds">等待命令执行的时间(单位:毫秒),
/// 如果设定为0,则无限等待</param>
/// <returns>返回DOS命令的输出</returns>
public static string Execute(string command, int seconds)
{

string output = ""; //输出字符串
if (command != null && !command.Equals(""))
{
Process process = new Process();//创建进程对象
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd.exe";//设定需要执行的命令
/*程序调用时将命令作为蚕食传入*/
startInfo.Arguments = "/C " + command;//“/C”表示执行完命令后马上退出
/*此处可以通过在不容命令之间加入& 或者换行符(\n\r)进行分割传入多个命令*/
//startInfo.Arguments = "/C dir & dir \n\r dir";
startInfo.UseShellExecute = false;//不使用系统外壳程序启动
startInfo.RedirectStandardInput = false;//不重定向输入
startInfo.RedirectStandardOutput = true; //重定向输出
startInfo.CreateNoWindow = true;//不创建窗口
process.StartInfo = startInfo;
try
{
if (process.Start())//开始进程
{
if (seconds == 0)
{
process.WaitForExit();//这里无限等待进程结束
}
else
{
process.WaitForExit(seconds); //等待进程结束,等待时间为指定的毫秒
}
output = process.StandardOutput.ReadToEnd();//读取进程的输出
}
}
catch
{
}
finally
{
if (process != null)
process.Close();
}
}
return output;
}

2. 调用Git Bush

调用Git Bush时可能与CMD有一些不同此时我的github是(GitHubSetup.exe)安装完成后由一个GUI和一个Bush。在平时使用Bush时直接打开的是安装目录下的git-bash.exe,但是如果通过C#调用的话是不行的不许调用 bin\bash.exe(具体原因我也不知道)。
而且不能像CMD的实例1那样写入命令,只能通过参数的方式写入。上代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/// <summary>
/// 执行Git命令
/// </summary>
/// <param name="command">要执行的命令</param>
public static void ExecuteGitCommand(string command)
{

Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = @"D:\Program Files\Git\bin\bash.exe";

/*此处可以通过在不容命令之间加入& 或者换行符(\n\r)进行分割传入多个命令*/
proc.StartInfo.Arguments = "-c \"" + command + "\"";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();

while (!proc.StandardOutput.EndOfStream)
{
Console.WriteLine(proc.StandardOutput.ReadLine());
}
}

public void RunGitBush(string command)
{

try
{
// create the ProcessStartInfo using "cmd" as the program to be run,
// and "/c " as the parameters.
// Incidentally, /c tells cmd that we want it to execute the command that follows,
// and then exit.
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo(@"D:\Program Files\Git\bin\bash.exe", "/c " + command);

// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
// Display the command output.
Console.WriteLine(result);
}
catch (Exception objException)
{
// Log the exception
}

}

3. 此外还可以通过Process的其他传参设置进行其他操作如

1
2
3
4
// 设置程序运行目录
processStartInfo.WorkingDirectory = @"E:\testgit";
//不显示程序窗口
p.StartInfo.CreateNoWindow = true;