我正在开发一个程序,使用 C# 和电报机器人来控制我的 VPS 中的 CMD。电报机器人和程序之间的连接效果很好,所以这不是问题。我想在同一个cmd窗口中从我的电报机器人编写命令。要将字符串命令发送到我使用的 cmd,请执行以下操作:
public static void Trythis(Message comando)
{
Process p = new Process();
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "cmd.exe";
info.RedirectStandardInput = true;
info.UseShellExecute = false;
String output = String.Empty;
p.StartInfo = info;
p.Start();
using (StreamWriter sw = p.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
sw.WriteLine(comando.Text);
}
}
using (StreamReader streamReader = p.StandardOutput)
{
output = streamReader.ReadToEnd();
Bot.SendTextMessageAsync(comando.Chat.Id, output);
}
}
}
但是我在这一部分得到无效操作异常:
using (StreamReader streamReader = p.StandardOutput)
{
output = streamReader.ReadToEnd();
Bot.SendTextMessageAsync(comando.Chat.Id, output);
}
从文档中:
无效操作异常。
尚未为重定向定义 StandardOutput 流;确保 ProcessStartInfo.RedirectStandardOutput 设置为 true,并将 ProcessStartInfo.UseShellExecute 设置为 false。
(或)
StandardOutput 流已打开,以便使用 BeginOutputReadLine 进行异步读取操作。
我认为您需要在开头添加这一行:
info.RedirectStandardOutput = true;
using
块的末尾调用包装对象上的Dispose()
...在第一次调用之后,您将关闭并处置您的流。