[英]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.