使用 C# 与控制台进行完全通信
Full comunication with console using C#
我正在使用 C# 和 Telegram 机器人开发一个程序来控制 VPS 中的 CMD。
Telegram bot 和 programm 之间的连接很好,所以这不是问题。
我想在同一个 cmd window 中从我的 Telegram 机器人编写命令。
要将字符串命令发送到我使用的 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);
}
}
}
但是我在这部分得到了 invalidOperationException:
using (StreamReader streamReader = p.StandardOutput)
{
output = streamReader.ReadToEnd();
Bot.SendTextMessageAsync(comando.Chat.Id, output);
}
InvalidOperationException.
The StandardOutput stream has not been defined for redirection; ensure ProcessStartInfo.RedirectStandardOutput is set to true and ProcessStartInfo.UseShellExecute is set to false.
(or)
The StandardOutput stream has been opened for asynchronous read operations with BeginOutputReadLine.
我认为您需要将这一行添加到开头:
info.RedirectStandardOutput = true;
using
块调用 Dispose()
包装对象的结尾......在第一次调用后,您将 关闭并处理您的流 .
我正在使用 C# 和 Telegram 机器人开发一个程序来控制 VPS 中的 CMD。 Telegram bot 和 programm 之间的连接很好,所以这不是问题。 我想在同一个 cmd window 中从我的 Telegram 机器人编写命令。 要将字符串命令发送到我使用的 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);
}
}
}
但是我在这部分得到了 invalidOperationException:
using (StreamReader streamReader = p.StandardOutput)
{
output = streamReader.ReadToEnd();
Bot.SendTextMessageAsync(comando.Chat.Id, output);
}
InvalidOperationException.
The StandardOutput stream has not been defined for redirection; ensure ProcessStartInfo.RedirectStandardOutput is set to true and ProcessStartInfo.UseShellExecute is set to false.
(or)
The StandardOutput stream has been opened for asynchronous read operations with BeginOutputReadLine.
我认为您需要将这一行添加到开头:
info.RedirectStandardOutput = true;
using
块调用 Dispose()
包装对象的结尾......在第一次调用后,您将 关闭并处理您的流 .