【发布时间】:2019-03-18 00:19:42
【问题描述】:
我想做的事
我想创建一个简单的 C# 应用程序,它创建一个运行 cmd.exe 的 Process 对象(应用程序的子进程),并在该 shell 中执行命令 echo "Hello World!"(或我指定的任何任意字符串在编译应用程序之前)。 C# 应用程序在构建并运行时,会创建并保持 shell 处于此状态:
尝试
我在 stackoverflow 和 MSDN 中搜索了示例,但很难找到正确的选项来设置 Process、ProcessStartInfo。特别是,我尝试了:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
/*
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "echo helloworld!";
string strCmdText;
process.StartInfo = startInfo;
process.Start();
*/
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = @"cmd.exe", // iexplorer.exe opened up ie!
Arguments = "",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = false,
WorkingDirectory = @"C:\Users\mtran\Desktop\ConsoleApp1",
WindowStyle = ProcessWindowStyle.Normal
}
};
proc.Start();
}
}
}
但是第二个 cmd 窗口(用于子进程)永远不会出现(如果我设置了RedirectStandardOutput = false),或者子进程的输出被写入父进程的 cmd 窗口。
【问题讨论】:
-
您希望新的 CMD 窗口在之后您的程序结束后保持打开吗?
-
@JuanR 是的。子进程的 CMD 窗口应保持打开状态。
标签: c# cmd process subprocess processstartinfo