Is it possible to log message to cmd.exe in C#/.Net?

后端 未结 5 2103
别跟我提以往
别跟我提以往 2021-01-05 19:19

Is it possible to log message from WinForms app to cmd.exe process started programmatically? I\'ve tried to do all kinds of variations of following code:

pri         


        
5条回答
  •  -上瘾入骨i
    2021-01-05 19:53

    Not the final answer, but it should help at least a little:

    First of all, declare that process outside your Log routine so it doesn't go out of scope when you want to log more.

    Anyway I tried the following:

    Process process = Process.Start(new ProcessStartInfo("cmd.exe", "/K more") {
      UseShellExecute = false,
      RedirectStandardInput = true,
      RedirectStandardError = true,
      RedirectStandardOutput = false
    });
    
    private void button1_Click(object sender, EventArgs e) {
      Log("Button has been pressed");
      MessageBox.Show(process.StandardError.ReadToEnd());
    }
    
    private void Log(string message) {
      process.StandardInput.WriteLine(message);
    }
    

    After clicking the button, your app will hang (it's waiting for the console to close, ReadToEnd literally reads to the end). When you close the console you will get a messagebox with the error output:

    The handle is invalid.
    The handle is invalid.
    The handle is invalid.
    'Button' is not recognized as an internal or external command,
    operable program or batch file.
    The handle is invalid.
    The handle is invalid.
    

    It seems not to be possible to redirect only the input without redirecting the output when running CMD. I'm not sure why, maybe trying different commandline options will help. I also tried removing the More command and logging "dir" instead:

    Log("dir");
    

    The result was a bit scary:

    The handle is invalid.
    ...
    There is not enough space on the disk.
    The handle is invalid.
    The handle is invalid.
    

    Interesting I must say! Looks like you've opened a can of worms :-)

提交回复
热议问题