--- lang: ja-jp breaks: true --- # C# 外部コマンドを実行する 2022-07-13 ## シンプルなバージョン ```csharp= static async Task<string?> ExecCmd( string cmd ) { // 第1引数がコマンド、第2引数がコマンドの引数 ProcessStartInfo processStartInfo = new ProcessStartInfo( @"cmd", @$"/c {cmd}" ); // ウィンドウを表示しない processStartInfo.CreateNoWindow = true; processStartInfo.UseShellExecute = false; // 標準出力、標準エラー出力を取得できるようにする processStartInfo.RedirectStandardOutput = true; processStartInfo.RedirectStandardError = true; // コマンド実行 string? standardOutput = null; string? standardError = null; int? exitCode = null; using (Process? process = Process.Start(processStartInfo)) { if (process != null) { // 標準出力・標準エラー出力・終了コードを取得する standardOutput = await process.StandardOutput.ReadToEndAsync() .ConfigureAwait(false); standardError = await process.StandardError.ReadToEndAsync() .ConfigureAwait(false); exitCode = process.ExitCode; process.Close(); } } return standardOutput; } ``` ## 標準出力、標準エラーを随時コンソールに出力するバージョン ```csharp= public static async Task<string> ExecCmdAsync( string cmd, bool outStandardOutput = true, bool outStandardError = true ) { // コマンド実行 StringBuilder sbrOutput = new(); StringBuilder sbrError = new(); int? exitCode = null; using (Process process = new()) { if (process != null) { ProcessStartInfo processStartInfo = process.StartInfo; processStartInfo.FileName = @"cmd"; processStartInfo.Arguments = @$"/c {cmd}"; // ウィンドウを表示しない processStartInfo.CreateNoWindow = true; processStartInfo.UseShellExecute = false; // 標準出力、標準エラー出力を取得できるようにする processStartInfo.RedirectStandardOutput = true; processStartInfo.RedirectStandardError = true; process.OutputDataReceived += (object sender, DataReceivedEventArgs e) => { string data = e.Data; sbrOutput.Append(data); if (outStandardOutput) { Console.WriteLine(data); } }; process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) => { string data = e.Data; sbrError.Append(data); if (outStandardError) { Console.WriteLine(data); } }; process.Start(); //非同期で出力の読み取りを開始 process.BeginOutputReadLine(); await process.WaitForExitAsync() .ConfigureAwait(false); exitCode = process.ExitCode; process.Close(); } } string standardOutput = sbrOutput.ToString(); string standardError = sbrError.ToString(); return standardOutput; } ``` ###### tags: `C#` `コマンド` `ProcessStartInfo`