我正在尝试以下代码
Process p = new Process();
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "cmd.exe";
info.RedirectStandardInput = true;
info.UseShellExecute = false;
p.StartInfo = info;
p.Start();
using (StreamWriter sw = new StreamWriter(p.StandardInput.BaseStream))
{
if (sw.BaseStream.CanWrite)
{
sw.WriteLine(@"dir");
}
}
using (StreamWriter sw = new StreamWriter(p.StandardInput.BaseStream))
{
if (sw.BaseStream.CanWrite)
{
sw.WriteLine(@"dir");
}
}
第一个sw.writeline正常,但第二个我发现这个过程是正确的。
进程退出的原因,以及如何让它继续运行以执行更多命令?
答案 0 :(得分:0)
将两个写入命令放在同一个使用块中,并省略第二个使用块。离开块后,using-block将丢弃StreamWriter。处理StreamWriter会关闭底层流并导致cmd退出。
答案 1 :(得分:0)
我解决了这个问题
static Queue<string> CmdQueue = new Queue<string>();
static Thread ThreadCMD = new Thread(new ThreadStart(CMDThread));
private static void CMDThread()
{
bool Active = true; // used to indicate the status of the session
ProcessStartInfo psiOpt = new ProcessStartInfo();
psiOpt.FileName = "cmd.exe";
psiOpt.WindowStyle = ProcessWindowStyle.Hidden;
psiOpt.RedirectStandardOutput = true;
psiOpt.RedirectStandardInput = true;
psiOpt.RedirectStandardError = true;
psiOpt.UseShellExecute = false;
psiOpt.CreateNoWindow = true;
Process procCommand = Process.Start(psiOpt);
procCommand.OutputDataReceived += ProcCommand_OutputDataReceived;
procCommand.ErrorDataReceived += ProcCommand_ErrorDataReceived;
procCommand.BeginOutputReadLine();
procCommand.BeginErrorReadLine();
using (StreamWriter sw = procCommand.StandardInput)
{
while (Active)
{
while (CmdQueue.Count==0) { }
string cmd = CmdQueue.Dequeue();
if (cmd != "cmdexit")
{
sw.WriteLine(cmd);
}
else
{
Active = false;
}
}
}
procCommand.OutputDataReceived -= ProcCommand_OutputDataReceived;
procCommand.ErrorDataReceived -= ProcCommand_ErrorDataReceived;
procCommand.Close();
}
private static void ProcCommand_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
PushCMDResult(Encoding.ASCII.GetBytes(e.Data));
}
private static void ProcCommand_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
PushCMDResult(Encoding.ASCII.GetBytes(e.Data));
}
public void StartCMD()
{
ThreadCMD.Start();
}
public void Execute(string cmd)
{
CmdQueue.Enqueue(cmd);
}
我可以启动cmd.exe会话,并使用execute执行所需数量的命令,以便将队列中的cmd字符串排入队列,该字符串将写入该编写器。 我也使用异步读取输出和错误。