简体   繁体   English

如何与C#代码中的命令提示符进行交互?

[英]How can I interact with the command prompt from C# code?

I am trying to interact with the windows command prompt from code. 我正在尝试从代码与Windows命令提示符进行交互。 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. 如果未设置RedirectStandardInput,则可以显示整个提示。 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. 而且,如果我关闭了StandardInput的编写器,则可以运行命令,但看不到提示或无法重复它。 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. 我希望重现Console2的命令行行为,但是它的源代码让我有点不知所措。

Check http://www.codeproject.com/cs/library/CommandLineHelper.asp 检查http://www.codeproject.com/cs/library/CommandLineHelper.asp

[marc_s] that URL results in a 404-page not found. [marc_s]该URL导致找不到404页。

The right URL most likely is: http://www.codeproject.com/KB/string/CommandLineHelper.aspx 正确的URL最有可能是: 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. 如果显示控制台命令Prompt,则将无法读取输出。 I think you need to draw your own command prompt if your reading the output of a process. 我认为如果您阅读进程的输出,则需要绘制自己的命令提示符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM