C#控制台启动程序或者执行命令

C#控制台启动程序或者执行命令

C#启动程序

调用示例

1
StartAConsoleProcess(ygcApiExePath);
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
private static void StartAConsoleProcess(string exePath, params string[] cmdText)
{
Process p = new Process();
p.StartInfo = new ProcessStartInfo(exePath);
p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动

if (exePath.Contains(Path.DirectorySeparatorChar))
{
var file = new FileInfo(exePath);
p.StartInfo.WorkingDirectory = file.Directory.FullName;
}

p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
p.StartInfo.CreateNoWindow = true;//不显示程序窗口
p.OutputDataReceived += YgcApi_OutputDataReceived;
p.ErrorDataReceived += YgcApi_ErrorDataReceived;
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
if (cmdText.Length > 0)
{
foreach (var item in cmdText)
{
p.StandardInput.WriteLine(item);
//向cmd窗口发送输入信息
p.StandardInput.AutoFlush = true;
}
}
}

调用cmd执行命令

调用示例:

1
RunCommand("cd D:\\viewerSevice", "d:", "dotnet Ygc.Service.3DViewerService.dll");
1
2
3
4
private static void RunCommand(params string[] cmdText)
{
StartAConsoleProcess(exePath: "cmd.exe", cmdText);
}