0

I'm working on a Discord bot that works as a middle man between my computer and me. Basically using my bot to send commands to another command prompt. The project itself is a console application as well. This is my approach: By using the start command the Discord Bot starts a new Cmd.exe process and replies back with it's Process ID.

Process.Start("Cmd.exe").Id;

Now by using that ID I try to get the process itself and try to write on that newly opened process but fail to do so miserably:

public static async Task ExecuteCommandAsync(int ID, string Command){
        var CMDProcess = Process.GetProcessById(ID);
        StreamWriter Writer = CMDProcess.StandardInput;
        await Writer.WriteLineAsync(Command);
}

    public static async Task<string> ReadOutputAsync(int ID)
    {
        var CMDProcess = Process.GetProcessById(ID);
        StreamReader Reader = CMDProcess.StandardOutput;
        return await Reader.ReadToEndAsync();
    }

I've looked through various examples posted online but can't get a simple answer. I want to keep the code itself short and simple.

  • You may have forgotten to set [RedirectStandardInput, RedirectStandardOutput, UseShellExecute properties](https://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo(v=vs.110).aspx) when starting the process, if you want to read from/write to its output/input streams. – kennyzx Jun 06 '17 at 03:38
  • I believe I've tried that way as well but I don't think RedirectStandardInput/Output is related to Process.Start()? Isn't it part of ProcessStartInfo? Or something like that? –  Jun 06 '17 at 12:11
  • 1
    Yes, use the overload Process.Start(ProcessStartInfo pInfo), set the said properties in the ProcessStartInfo instance. – kennyzx Jun 06 '17 at 12:29
  • Possible duplicate of https://stackoverflow.com/questions/4291912/process-start-how-to-get-the-output. I'm pretty sure that will solve your problem. – Jim Mischel Jun 06 '17 at 14:22
  • Also see https://stackoverflow.com/a/4291965/56778 – Jim Mischel Jun 06 '17 at 14:27
  • I tried that way but the process doesn't start at all. –  Jun 06 '17 at 19:28

0 Answers0