首先,一些背景信息。我编写了一个应用程序,可以与cmd.exe进行实时连接。
问题: 我想要多次写入而不关闭cmd.exe的进程。这会导致错误,因为在能够检索任何输出之前,我必须关闭StreamWriter,而在接收到输出后,我想再次写入它。
示例:
我想要使用命令cd C:\
并接收更改路径的输出。之后,我想通过使用dir
查看C:\目录中有哪些文件。
我不希望进程重新启动,因为它会重置路径。
我知道我可以简单地使用dir C:\
,但这不是重点。
这只是一个简短的例子,我想用它来解决许多其他需要解决此问题的事情。
class Program
{
static void Main(string[] args)
{
ProcessStartInfo pInfo = new ProcessStartInfo();
pInfo.RedirectStandardInput = true;
pInfo.RedirectStandardOutput = true;
pInfo.RedirectStandardError = true;
pInfo.UseShellExecute = false;
pInfo.CreateNoWindow = true;
pInfo.FileName = "cmd.exe";
Process p = new Process();
p.StartInfo = pInfo;
bool pStarted = false;
Console.Write("Command: ");
string command = Console.ReadLine();
while (command != "exit")
{
if (!pStarted && command == "start")
{
p.Start();
Console.WriteLine("Process started.");
pStarted = true;
}
else if (pStarted)
{
StreamWriter sWriter = p.StandardInput;
if (sWriter.BaseStream.CanWrite)
{
sWriter.WriteLine(command);
}
sWriter.Close();
string output = p.StandardOutput.ReadToEnd();
string error = p.StandardError.ReadToEnd();
Console.WriteLine("\n" + output + "\n");
}
Console.Write("\nCommand: ");
command = Console.ReadLine();
}
Console.WriteLine("Process terminated.");
Console.ReadKey();
}
}
有人知道我如何保持一个进程并多次写入它,每次都接收输出吗?
提前致谢。
编辑:这可能与以下问题略有相似:使用.NET执行多个命令行的相同进程。链接的问题没有有用的答案,并且在多个方面不同。我面临的一个巨大问题是,我希望在用户发送每个命令后打印输出。