问题描述
我试图使用 StandardInput.WriteLine(str)
发送命令到一个打开的cmd.exe进程,但是没有一个命令似乎被发送。首先我打开一个进程,使用全局变量p( Process p
)。
I am trying to send commands to an open cmd.exe process using StandardInput.WriteLine(str)
, however none of the commands seem to be sent. First I open a process, with a global variable p (Process p
).
p = new Process()
{
StartInfo = {
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
FileName = @"cmd.exe",
Arguments = "/C" //blank arguments
}
};
p.Start();
p.WaitForExit();
之后,我尝试使用一个简单的方法发送一个命令, 。
After, I try to send a command using a simple method, that logs the result in a text box.
private void runcmd(string command)
{
p.StandardInput.WriteLine(command);
var output = p.StandardOutput.ReadToEnd();
TextBox1.Text = output;
}
现在我用 DIR
,但
var output
显示为null,这将导致没有输出。有没有更好的方法发送命令到打开cmd.exe过程?
Right now I am testing it with
DIR
, but var output
shows up as null, which results in no output. Is there a better way to send a command to the open cmd.exe process?
推荐答案
推荐答案
我永远不能让它工作同步读取stdout而不关闭stdin,但它对stdout / stderr的异步读取工作。不需要传入
/ c
,只有在传递命令参数时才这样做;你不是这样做的,你是直接发送命令到输入。
I could never get it to work with synchronous reads of stdout without closing stdin, but it does work with async reading for stdout/stderr. No need to pass in
/c
, you only do that when passing in a command through the arguments; you are not doing this though, you are sending the command directly to the input.
var p = new Process()
{
StartInfo = {
CreateNoWindow = false,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
FileName = @"cmd.exe"}
};
p.OutputDataReceived += (sender, args1) => Console.WriteLine(args1.Data);
p.ErrorDataReceived += (sender, args1) => Console.WriteLine(args1.Data);
p.Start();
p.BeginOutputReadLine();
p.StandardInput.WriteLine("dir");
p.StandardInput.WriteLine("cd e:");
p.WaitForExit();
Console.WriteLine("Done");
Console.ReadLine();
这篇关于无法向cmd.exe进程发送命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!