如何解决使用 C# 重定向从批处理文件调用的可执行文件的输入和输出
我正在努力实现的目标:
一个简单的 c# 类,用于向 Xilinx Vivado 应用程序发送和接收 TCL 命令。 vivado 中已经有一个内置的 TCL shell 控制台,它所做的只是调用带有一些参数 (-mode tcl) 的批处理文件 (vivado.bat)。这个批处理文件的工作方式如下:
=== vivado.bat ==
@echo off
setlocal
set ... *configure a few environment variables..
call myBatchFile#1.bat
set ... *configure a few environment variables..
call myBatchFile#2.bat
set ... *configure a few environment variables..
call myBatchFile#3.bat
exit
其中 myBatchFile#1.bat 和 myBatchFile#2.bat 设置了更多的环境变量,而 myBatchFile#3.bat 在内部调用第 4 个批处理文件 (myBatchFile#4.bat),最终启动可执行文件:>
=== myBatchFile#4.bat ===
set ... *configure a few environment variables..
C:/myPathToExe/vivado.exe -mode tcl
set ... *configure a few more environment variables..
到目前为止我尝试过的:
我想出了下面的示例代码:
- UseShellExecute 必须设置为 false,因为我需要重定向输入和输出。
- 由于 UseShellExecute 设置为 false,我无法直接运行批处理文件。作为一种解决方法,我运行“cmd.exe”并将批处理文件作为参数传递。
- 输出在输出事件触发时存储在缓冲区中(收到换行符)。注意:输出缓冲区已被定义为一个队列,以便能够从缓冲区中仅返回 1 行或一次返回所有行(就像 ReadLine、ReadAll 方法一样)。
public Process VivadoConsole = new Process();
private Queue _OutputBuffer = new Queue();
private string _ErrorBuffer;
VivadoConsole.StartInfo.FileName = "cmd.exe";
VivadoConsole.StartInfo.Arguments = "START /b /wait \"vivado\" CMD /s /c \"vivado.bat -mode tcl\"";
VivadoConsole.StartInfo.WorkingDirectory = @"C:\Xilinx\Vivado\2019.1\bin";
VivadoConsole.StartInfo.UseShellExecute = false;
VivadoConsole.StartInfo.RedirectStandardOutput = true;
VivadoConsole.StartInfo.RedirectStandardError = true;
VivadoConsole.StartInfo.RedirectStandardInput = true;
VivadoConsole.StartInfo.Verb = "runas";
VivadoConsole.StartInfo.ErrorDialog = false;
VivadoConsole.OutputDataReceived += (object sender,DataReceivedEventArgs e) =>
{
if (!String.IsNullOrEmpty(e.Data))
{
_OutputBuffer.Enqueue(e.Data);
}
};
VivadoConsole.ErrorDataReceived += (object sender,DataReceivedEventArgs e) =>
{
_ErrorBuffer += e.Data;
};
VivadoConsole.EnableRaisingEvents = true;
VivadoConsole.Start();
VivadoConsole.BeginOutputReadLine();
VivadoConsole.BeginErrorReadLine();
_OutputBuffer.Clear();
问题
无论 START/CALL/CMD(带有参数:/b /c /i /k /wait)的哪种组合,我都用来启动“Vivado.bat -mode tcl”文件,但我无法获取我的应用程序上班。我确信输出已正确重定向,导致我将“飞溅”文本放入我的 outputBuffer 变量中,控制台通常在加载时输出该变量。但即使在那之后,使用
VivadoConsole.StandardInput.WriteLine(str);
什么都不做。我注意到,如果我不重定向输入并直接输入到应用程序控制台窗口中,它会起作用(尽管我必须两次输入每个命令)。对我来说,从批处理文件中重定向输入似乎没有按预期工作(我尝试了几种结束行字符的组合,但都不起作用)...
老实说,我不知道我错过了什么或我做错了什么,但我唯一的其他选择是手动加载每个环境变量,然后调用 exe 文件,所有这些都来自同一个控制台窗口(尽管我不知道这是否可行...)
我更喜欢不需要修改批处理文件的任何解决方案,因为它是第 3 方应用程序。但是,如果在不实际修改批处理文件的情况下无法做到这一点,那么它也将受到欢迎。
提前致谢。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。