2

如果我在哪里有可执行文件:(可执行文件不是 ac# 应用程序,它包含非托管代码,但代码相似)

// 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");
    }
}

那我怎么SomeMethodA()能从c#执行呢?

这是我到目前为止所做的

        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! 
        }
4

1 回答 1

2

如果您只是想传递“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
    }

如果您想一起绕过输入过程,那将是一个更难的问题(如果该方法不是私有的,那会更容易),我将删除我的答案。


PS您应该将您的两个流阅读器包装在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");
    }
}
于 2012-12-21T06:07:24.070 回答