4

コマンドが行の場合、以下のコードは機能します。

Process p = new Process()
{
    StartInfo = new ProcessStartInfo("cmd")
    {
       UseShellExecute = false,
       RedirectStandardInput = true,
       RedirectStandardOutput = true,
       CreateNoWindow = true,
       Arguments = String.Format("/c \"{0}\"", command),
    }
};
p.OutputDataReceived += (s, e) => Messagebox.Show(e.Data);
p.Start();
p.BeginOutputReadLine();
p.WaitForExit();

しかし、WriteLine() のような一連のコマンドはどうでしょうか。

p.StandardInput.WriteLine("cd...");
p.StandardInput.WriteLine("dir");

この状況で出力を取得するにはどうすればよいですか?

4

1 に答える 1

4

このような動作を実現するには、/kswitch を使用cmd.exeして対話モードで実行する必要があります。

問題は、異なるコマンドからの入力を分離することです。これを行うには、次のpromptコマンドを使用して標準プロンプトを変更できます。

prompt --Prompt_C2BCE8F8E2C24403A71CA4B7F7521F5B_F659E9F3F8574A72BE92206596C423D5 

そのため、コマンド出力の終わりを判断するのは非常に簡単です。

完全なコードは次のとおりです。

public static IEnumerable<string> RunCommands(params string[] commands) {
    var process = new Process {
        StartInfo = new ProcessStartInfo("cmd") {
            UseShellExecute = false,
            RedirectStandardInput = true,
            RedirectStandardOutput = true,
            CreateNoWindow = true,
            Arguments = "/k",
        }
    };

    process.Start();

    const string prompt = "--Prompt_C2BCE8F8E2C24403A71CA4B7F7521F5B_F659E9F3F8574A72BE92206596C423D5 ";

    // replacing standard prompt in order to determine end of command output
    process.StandardInput.WriteLine("prompt " + prompt);
    process.StandardInput.Flush();
    process.StandardOutput.ReadLine();
    process.StandardOutput.ReadLine();

    var result = new List<string>();

    try {
        var commandResult = new StringBuilder();

        foreach (var command in commands) {
            process.StandardInput.WriteLine(command);
            process.StandardInput.WriteLine();
            process.StandardInput.Flush();

            process.StandardOutput.ReadLine();

            while (true) {
                var line = process.StandardOutput.ReadLine();

                if (line == prompt) // end of command output
                    break;

                commandResult.AppendLine(line);
            }

            result.Add(commandResult.ToString());

            commandResult.Clear();

        }
    } finally {
        process.Kill();
    }

    return result;
}

うまく機能しますが、1 つの大きなハックのように見えます。

代わりにコマンドごとにプロセスを使用することをお勧めします。

于 2013-04-08T04:42:09.823 に答える