C# 与 CLI 进程的对话
Posted
技术标签:
【中文标题】C# 与 CLI 进程的对话【英文标题】:C# Dialogue with CLI Process 【发布时间】:2020-11-26 13:07:09 【问题描述】:我想在 Windows 控制台中运行一个进程,然后,我想通过(通过按钮单击)一些命令并在 RichTextBox 中查看结果。
我能够启动程序并在启动后读取响应,但是当我尝试发送任何命令时,它不起作用。我无法用这个过程“说话”……
如果您有任何想法。我会欣然接受!
代码下方:
public static void SortOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
// Collect the sort command output.
if (!String.IsNullOrEmpty(outLine.Data))
numOutputLines++;
// Add the text to the collected output.
sortOutput.Append(Environment.NewLine + $"[numOutputLines] - outLine.Data");
//RichTextBox
MCM.ActiveForm.Invoke(MCM.AffichageTextDelegate, new object[] outLine.Data );
public static async Task<int> RunProcessAsync()
using (var process = new Process
StartInfo =
FileName = "AAA.exe",
Arguments = “-v COM74",
UseShellExecute = false,
CreateNoWindow = false,
RedirectStandardOutput = true,
RedirectStandardInput = true,
RedirectStandardError = true
,
EnableRaisingEvents = true
)
return await RunProcessAsync(process).ConfigureAwait(false);
private static Task<int> RunProcessAsync(Process process)
var tcs = new TaskCompletionSource<int>();
process.Exited += (s, ea) => tcs.SetResult(process.ExitCode);
process.OutputDataReceived += (s, ea) => Console.WriteLine(ea.Data);
sortOutput = new StringBuilder();
process.OutputDataReceived += SortOutputHandler;
process.ErrorDataReceived += (s, ea) => Console.WriteLine("ERR: " + ea.Data);
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
return tcs.Task;
private async void Btn_Click(object sender, EventArgs e)
await RunProcessAsync();
【问题讨论】:
你是如何向进程发送命令的? 我试过了:Console.WriteLine。它是在控制台中编写的,但该过程没有回答。当我使用 StandardInput 时它不起作用,我认为这是因为我重新启动了一个新进程,我没有在第一个进程中写入。 【参考方案1】:它使用同步过程:
public static Process myProcess;
public static StreamWriter myStreamWriter;
Process myProcess = new Process();
myProcess.StartInfo.FileName = "AAA.exe";
myProcess.StartInfo.Arguments = '-' + "p" + " " + ComboBoxPortCom.Text;
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardInput = true;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.StartInfo.RedirectStandardError = true;
myProcess.OutputDataReceived += (s, ea) => Console.WriteLine(ea.Data);
sortOutput = new StringBuilder();
myProcess.OutputDataReceived += SortOutputHandler;
myProcess.ErrorDataReceived += (s, ea) => Console.WriteLine("ERR: " + ea.Data);
myProcess.Start();
myProcess.BeginOutputReadLine();
myProcess.BeginErrorReadLine();
myStreamWriter = myProcess.StandardInput;
myStreamWriter.WriteLine("Command1" + '\n');
【讨论】:
以上是关于C# 与 CLI 进程的对话的主要内容,如果未能解决你的问题,请参考以下文章