0

I'm trying to make a C# program that can listen for and output to cmd.exe and log it to file. For example, if I run an exe and it runs a command in cmd like echo "hello", I want echo "hello" to be written in a file.

I know I need to use FileSystem, as well as Process maybe?

If this is even possible, and help would really be appreciated. Thanks.

Broots Waymb
  • 4,713
  • 3
  • 28
  • 51
kjsmita6
  • 458
  • 1
  • 6
  • 21

1 Answers1

1

Here's a quick little example that should work. There are a lot of examples out there, I'll try looking on stackoverflow and post one as well...

    string cmd_to_run = "dir"; // whatever you'd like this to be...

    // set up our initial parameters for out process
    ProcessStartInfo p_info = new ProcessStartInfo();
    p_info.FileName = "cmd";
    p_info.Arguments = "/c " + cmd_to_run;
    p_info.UseShellExecute = false;

    // instantiate a new process
    Process p_to_run = new Process();
    p_to_run.StartInfo = p_info;

    // wait for it to exit (I chose 120 seconds)
    // waiting for output here is not asynchronous, depending on the task you may want it to be
    p_to_run.Start();
    p_to_run.WaitForExit(120 * 1000);

    string output = p_to_run.StandardOutput.ReadToEnd();  // here is our output

Here's the Process class MSDN overview (there's a quick example on this page): https://msdn.microsoft.com/en-us/library/system.diagnostics.process(v=vs.110).aspx

And here's a SO example dealing with calling ReadToEnd() on Process: StandardOutput.ReadToEnd() hangs

Community
  • 1
  • 1