使用C#Console App在Cmd.Exe中执行命令时打开新进程窗口时出现问题

时间:2018-07-17 02:09:34

标签: c# .net cmd console-application windows-console

我有一个下面的代码,使用.Net控制台在cmd.exe中执行一系列命令。 我需要在每次执行命令时打开新的cmd窗口,以便可以将其可视化。 但是下面的代码虽然成功执行了所有命令,但没有打开新窗口;我已经设置了窗口属性。请帮忙。

 //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();
                    }
                }

            }

1 个答案:

答案 0 :(得分:1)

这将打开外壳,启动可执行文件,并在进程结束时保持外壳窗口打开,注意/ K标志,您需要包括此标志/开关,例如:

Process p = new Process();
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "CMD.EXE";
psi.Arguments = "/K yourmainprocess.exe";
p.Start(psi);
p.WaitForExit();

在您的代码中:

ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", "/k /c " + _command);