In a separate process, the console opens to which the command is transferred. I want to get the result of the command, which, instead of outputting to the console, should be saved in a variable of type string and returned to the calling method. Here is the code that does not work:
internal class ConsoleBuilder { private static int lineCount = 0; private static StringBuilder output = new StringBuilder(); internal static void Execute(string command, ref Process proc, out string outputText, out string outputError) { outputText = string.Empty; outputError = string.Empty; proc = new Process(); proc.StartInfo = new ProcessStartInfo("C:\\Windows\\System32\\cmd.exe", command); proc.StartInfo.CreateNoWindow = true; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.RedirectStandardOutput = true; proc.EnableRaisingEvents = true; proc.OutputDataReceived += new DataReceivedEventHandler((sender, e) => { if(!String.IsNullOrEmpty(e.Data)) { lineCount++; output.Append("\n[" + lineCount + "]: " + e.Data); } }); proc.Start(); proc.BeginOutputReadLine(); proc.BeginErrorReadLine(); outputText = output.ToString(); } } internal class Program { private static void Main(string[] args) { string command = "echo I'm here!"; string pathToCmd = "C:\\Windows\\System32\\cmd.exe"; Process proc = null; string outputText = string.Empty; string outputError = string.Empty; ConsoleBuilder.Execute(command, ref proc, out outputText, out outputError); Console.WriteLine(outputText); } } The outputText string is returned empty. Tell me what's wrong?