如何通过 C# 代码与命令提示符交互?
我正在尝试通过代码与 Windows 命令提示符进行交互。我的目标是显示提示,输入一些命令,显示输出,然后重复。但似乎无法让前三个同时工作。
private void button2_Click(object sender, EventArgs e)
{
Process proc = new Process();
proc.StartInfo.FileName = "cmd";
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardInput = true;
proc.Start();
StreamReader k = new StreamReader(proc.StandardOutput.BaseStream);
textBox2.Text = k.ReadToEnd();
}
上面的代码只是挂起。如果我不设置 RedirectStandardInput,那么我可以显示整个提示。如果我关闭 StandardInput 的编写器,我可以获得要运行的命令,但看不到提示,也无法重复它。那么我怎样才能得到提示显示,运行命令,并显示输出......重复?
我希望重现 Console2 的命令行行为,但我对它的源代码有点不知所措。
I am trying to interact with the windows command prompt from code. My goal is to display the prompt, put in some command, display the output, and repeat. But can't seem to get the first three working at the same time.
private void button2_Click(object sender, EventArgs e)
{
Process proc = new Process();
proc.StartInfo.FileName = "cmd";
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardInput = true;
proc.Start();
StreamReader k = new StreamReader(proc.StandardOutput.BaseStream);
textBox2.Text = k.ReadToEnd();
}
The above code just hangs. If I don't set RedirectStandardInput, then I can display the entire prompt. And if I close the writer for StandardInput I can get a command to run, but without seeing the prompt, or being able to repeat it. So how can I get the prompt to show, run a command, and show the output ... repeatedly?
I am hoping to reproduce the command line behavior of Console2 but I am a little overwhelmed by it's source code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
检查 http://www.codeproject.com/cs/library/CommandLineHelper.asp
[marc_s] 该 URL 导致找不到 404 页面。
正确的 URL 最有可能是: http://www.codeproject.com/KB/string /CommandLineHelper.aspx
Check http://www.codeproject.com/cs/library/CommandLineHelper.asp
[marc_s] that URL results in a 404-page not found.
The right URL most likely is: http://www.codeproject.com/KB/string/CommandLineHelper.aspx
我认为你不能。如果显示控制台命令提示符,您将无法读取输出。我认为如果您阅读进程的输出,您需要绘制自己的命令提示符。
I think you cant. If you show the console command Prompt, you wont be able to read the output. I think you need to draw your own command prompt if your reading the output of a process.