Thursday, June 26, 2014

.NET C#: Running command line in CMD and waiting for it to finish

I had a script that i should call with command line interface, then other tasks that should be done after that.
I used the Process and ProcessStartInfo as below, but the problem i had is that the script was taking some time, and the program execution was failing after that since the script is not finished yet.

            using (Process process = new Process())
            {
                var startInfo = new ProcessStartInfo("cmd")
                {
                    RedirectStandardInput = true,
                    RedirectStandardOutput = true,
                    WindowStyle = ProcessWindowStyle.Normal,
                    UseShellExecute = false,
                    CreateNoWindow = false
                };

                process.StartInfo = startInfo;
                process.OutputDataReceived += (sender, e) => Console.WriteLine(e.Data);
                process.Start();
                process.StandardInput.Write("script"+ process.StandardInput.NewLine);
                process.Close();
            }

I wanted to make sure that the program execution waits till the script finishes.So instead of using Close method, i added WaitForExit, and i am manually sending exit command to the command line after the script finishes, like below

            using (Process process = new Process())
            {
                var startInfo = new ProcessStartInfo("cmd")
                {
                    RedirectStandardInput = true,
                    RedirectStandardOutput = true,
                    WindowStyle = ProcessWindowStyle.Normal,
                    UseShellExecute = false,
                    CreateNoWindow = false
                };

                process.StartInfo = startInfo;
                process.OutputDataReceived += (sender, e) => Console.WriteLine(e.Data);
                process.Start();
                process.StandardInput.Write("script"+ process.StandardInput.NewLine);
                process.StandardInput.Write("exit" + process.StandardInput.NewLine);
                process.WaitForExit();
            }

This worked for me and the program execution waited till the script finishes.

No comments:

Post a Comment