Reputation: 613
I have a below code to execute series of commands in cmd.exe using .Net console. I have requirement to open new cmd window each time the command executes, so that it can be visualized. But below code not opening new window although it executes all commands successfully; I have set window property. Please help.
//Sample Commands
List<string> mockobject = new List<string>();
mockobject.Add("type nul >File1.txt");
mockobject.Add("echo This is a sample text file > File2.txt");
mockobject.Add("type nul >File3.txt");
foreach (string _command in mockobject)
{
ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", "/c " + _command);
procStartInfo.WorkingDirectory = ProcessDirectory;
procStartInfo.RedirectStandardError = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = false;
procStartInfo.WindowStyle = ProcessWindowStyle.Maximized;
using (Process process = new Process())
{
process.StartInfo = procStartInfo;
process.Start();
// wait until process does its work
process.WaitForExit();
// read the result if any
if(process.ExitCode != 0)
{
string result = process.StandardError.ReadToEnd();
}
}
}
Upvotes: 1
Views: 287
Reputation: 65692
This will open the shell, start your executable and keep the shell window open when the process ends, notice the /K flag, you need to include this flag/switch, eg:
Process p = new Process();
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "CMD.EXE";
psi.Arguments = "/K yourmainprocess.exe";
p.Start(psi);
p.WaitForExit();
In your code:
ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", "/k /c " + _command);
Upvotes: 1