windows 来自 cmd.exe shell 的输入和输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6165517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Input & Output from cmd.exe shell
提问by surfline
I am trying to create a Windows Forms C# project that interacts with the command prompt shell (cmd.exe).
我正在尝试创建一个与命令提示符 shell (cmd.exe) 交互的 Windows 窗体 C# 项目。
I want to open a command prompt, send a command (like ipconfig) and then read the results back into the windows form into a string, textbox, or whatever.
我想打开一个命令提示符,发送一个命令(如 ipconfig),然后将结果读回到 windows 窗体中,转换为字符串、文本框或其他任何内容。
Here is what I have so far, but I am stuck. I cannot write or read to the command prompt.
这是我到目前为止所拥有的,但我被卡住了。我无法写入或读取命令提示符。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
namespace WindowsFormsApplication1
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/k dir *.*";
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
StreamWriter inputWriter = p.StandardInput;
StreamReader outputWriter = p.StandardOutput;
StreamReader errorReader = p.StandardError;
p.WaitForExit();
}
}
}
Any help would be greatly appreciated.
任何帮助将不胜感激。
Thanks.
谢谢。
回答by IAmTimCorey
Here is a SO question that will give you the information you need:
这是一个 SO 问题,它将为您提供所需的信息:
How To: Execute command line in C#, get STD OUT results
Basically, you ReadToEnd on your System.IO.StreamReader.
基本上,您在 System.IO.StreamReader 上 ReadToEnd。
So, for example, in your code you would modify the line StreamReader errorReader = p.StandardError;
to read
因此,例如,在您的代码中,您将修改该行StreamReader errorReader = p.StandardError;
以读取
using(StreamReader errorReader = p.StandardError)
{
error = myError.ReadToEnd();
}
回答by S P
var yourcommand = "<put your command here>";
var procStart = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + yourcommand);
procStart.CreateNoWindow = true;
procStart.RedirectStandardOutput = true;
procStart.UseShellExecute = false;
var proc = new System.Diagnostics.Process();
proc.StartInfo = procStart;
proc.Start();
var result = proc.StandardOutput.ReadToEnd();
Console.WriteLine(result);