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
    }

入力プロセスをすべてバイパスしたい場合、それははるかに難しい問題です (メソッドがプライベートでない場合は簡単です)。回答を削除します。


usingPS 2 つのストリーム リーダーをステートメントでラップする必要があります

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 に答える