如果我在哪里有可执行文件:(可执行文件不是 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!
}
最佳答案
如果您只是想传递“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
}
如果您想完全绕过输入过程,这是一个更难的问题(如果方法不是私有(private)的,那就更容易了),我将删除我的答案。
附注您应该将两个流读取器包装在 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");
}
}
关于c# - 从我自己的控制台应用程序在第 3 方 exe 上执行方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13984325/