我想发送带参数的命令并从 cmd 读取它们的答案。因此,我编写了下面的代码,但它无法正常工作并锁定在屏幕上(myString 通常为 null - "")。我只想将命令发送到打开的命令提示符。哪里有问题?提前致谢。 (例如:如何获取 ping 请求的结果?)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
namespace CallBatchFile
{
class Program
{
[STAThread]
static void Main()
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c date";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string myString = p.StandardOutput.ReadToEnd();
p.WaitForExit();
}
}
}
最佳答案
cmd/c date
正在阻塞。你可以使用
p.StartInfo.Arguments = "/c date /T";
要停止等待输入的日期,或者输入cmd
p.StartInfo.RedirectStandardInput = true;
...
p.StandardInput.Write("\n");
..或读取异步,以便您可以在 cmd 等待您的输入时获取输出:
p.BeginOutputReadLine();
p.OutputDataReceived += (_, e) => Console.WriteLine(e.Data);
关于c# - 在C#中发送cmd命令并读取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24649282/