[英]input from console application to another c# console application?
我想开发输入到另一个C#应用程序(b.exe)
ac#应用程序(a.exe)
, b.exe
不带任何参数。
b.exe -call or b.exe call
等不起作用
当我从cmd打开b.exe
,它会接受如下所示的参数:
b:call
b:command 2
....
b:command n
如何从a.exe
喂b.exe
?
我已经用过了,但是没有用。
var psi = new ProcessStartInfo("b.exe")
{
RedirectStandardInput = true,
RedirectStandardOutput = false,
UseShellExecute = false
};
var p = new Process { StartInfo = psi };
p.Start();
p.StandardInput.WriteLine("call");
这是我从您的问题中了解的内容:
a.exe
启动b.exe
a.exe
使用命令行参数或标准输入将命令/请求传递给b.exe
b.exe
收到命令/请求并通过StandardOutput传递信息 使用命令行参数要简单一些,除非您需要为每个请求/命令多次运行b.exe
。
// b.exe
static void Main(string[] args)
{
// using command line arguments
foreach (var arg in args)
ProcessArg(arg);
// if using input, then use something like if processing line by line
// string line = Console.ReadLine();
// while (line != "exit" || !string.IsNullOrEmpty(line))
// ProcessArg(line);
// or you can read the input stream
var reader = new StreamReader(Console.OpenStandardInput());
var text = reader.ReadToEnd();
// TODO: parse the text and find the commands
}
static void ProcessArg(string arg)
{
if (arg == "help") Console.WriteLine("b.exe help output");
if (arg == "call") Console.WriteLine("b.exe call output");
if (arg == "command") Console.WriteLine("b.exe command output");
}
// a.exe
static void Main(string[] args)
{
// Testing -- Send help, call, command --> to b.exe
var psi = new ProcessStartInfo("b.exe", "help call command")
{
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
UseShellExecute = false,
};
var p = new Process() { StartInfo = psi };
p.ErrorDataReceived += p_ErrorDataReceived;
p.OutputDataReceived += p_OutputDataReceived;
p.Start();
p.BeginErrorReadLine();
p.BeginOutputReadLine();
// if sending data through standard input (May need to use Write instead
// of WriteLine. May also need to send end of stream (0x04 or ^D / Ctrl-D)
StreamWriter writer = p.StandardInput;
writer.WriteLine("help");
writer.WriteLine("call");
writer.WriteLine("exit");
writer.Close();
p.WaitForExit();
}
static void p_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
Console.Error.WriteLine("a.exe error: " + e.Data ?? "(null)");
}
static void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine("a.exe received: " + e.Data ?? "(null)");
}
查看这些方法中的OutputDataReceived和ErrorDataReceived事件以及MSDN示例。
需要考虑的一个因素是,您无法通过管道以管理员身份运行的程序的输出。 您将需要保存输出,然后将输出传递给其他程序。
不久前,我发现了一个带有ProcessRunner类的有用的CSharpTest库。 浏览ProcessRunner的“ InternalStart”方法作为示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.