如果我在哪里有可执行文件:(可执行文件不是c#应用程序,它包含非托管代码,但代码类似)
// ConsoleApplication1.exe
class Program
{
static void Main()
{
while (true)
{
System.Console.WriteLine("Enter command");
var input = System.Console.ReadLine();
if (input == "a")
SomeMethodA();
else if (input == "b")
SomeMethodB();
else if (input == "exit")
break;
else
System.Console.WriteLine("invalid command");
}
}
private static void SomeMethodA()
{
System.Console.WriteLine("Executing method A");
}
private static void SomeMethodB()
{
System.Console.WriteLine("Executing method B");
}
}
然后我怎么能从c#执行SomeMethodA()
?
这是我到目前为止所做的工作
Process p = new Process();
var procStartInfo = new ProcessStartInfo(@"ConsoleApplication1.exe")
{
UseShellExecute = false,
RedirectStandardOutput = true,
};
p.StartInfo = procStartInfo;
p.Start();
StreamReader standardOutput = p.StandardOutput;
var line = string.Empty;
while ((line = standardOutput.ReadLine()) != null)
{
Console.WriteLine(line);
// here If I send a then ENTER I will execute method A!
}
答案 0 :(得分:1)
如果您只想传递“a”以便SomeMethodA执行,您可以执行此操作
Process p = new Process();
var procStartInfo = new ProcessStartInfo(@"ConsoleApplication1.exe")
{
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardInput = true, //New Line
};
p.StartInfo = procStartInfo;
p.Start();
StreamReader standardOutput = p.StandardOutput;
StreamWriter standardInput = p.StandardInput; //New Line
var line = string.Empty;
//We must write "a" to the other program before we wait for a answer or we will be waiting forever.
standardInput.WriteLine("a"); //New Line
while ((line = standardOutput.ReadLine()) != null)
{
Console.WriteLine(line);
//You can replace "a" with `Console.ReadLine()` if you want to pass on the console input instead of sending "a" every time.
standardInput.WriteLine("a"); //New Line
}
如果你想要一起绕过输入过程这是一个更难的问题(如果方法不是私有的话会更容易),我会删除我的答案。
P.S。你应该将你的两个流阅读器包装在using
语句
using (StreamReader standardOutput = p.StandardOutput)
using (StreamWriter standardInput = p.StandardInput)
{
var line = string.Empty;
standardInput.WriteLine("a");
while ((line = standardOutput.ReadLine()) != null)
{
Console.WriteLine(line);
standardInput.WriteLine("a");
}
}