I am trying to run command line from my c# program. to keep it simple all i am doing is running “dir” command. then i read each line of the result. when i reach the end of the output the program hangs. it does not do anything. Below is the program.
static void Main(string[] args)
{
ProcessStartInfo startInfo = new ProcessStartInfo("Cmd.exe");
startInfo.UseShellExecute = false;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
List<string> output = new List<string>();
process.StandardInput.WriteLine("dir");
process.StandardInput.Flush();
while (process.StandardOutput.ReadLine() != null)
{
output.Add(process.StandardOutput.ReadLine());
}
process.WaitForExit();
process.Kill();
}
Cmd.exedoesn’t exit until you tell it to – you’re waiting for it to complete, but it’s waiting for your next command.Try
process.StandardInput.WriteLine("exit");to tell the process to quit.