简体   繁体   中英

How to redirect standard output when spawning a process

I've built a webservice for an internal server that I want to send a command to and have it launch a process. So I want to send a command to it like this:

http://machine:999/execute?path=c:\scripts\dostuff.exe&args=-test

The endpoint would then do something like this:

public ActionResult(string path, string args)
{

    var proc = new System.Diagnostics.Process();
    proc.StartInfo.FileName = path;
    proc.StartInfo.Arguments = args;
    proc.StartInfo.UseShellExecute = false;
    proc.StartInfo.CreateNoWindow = true;
    proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
    proc.StartInfo.RedirectStandardOutput = true;

    //Hook into all standard output here

    //Block until process is returned - Async Controller action

    return Content(output.ToString())
}

I want to be able to capture all the error messages and standard output generated by the executable. The executable could be anything like a console application or a powershell script. What's the best approach for doing something like this?

Use proc.StandardOutput.ReadToEnd() to read the redirected output stream to the end, and return that.

You may also want to set RedirectStandardError to True and do the same thing with proc.StandardError to get the error messages. You can spawn a background thread to synchronously read standard error alongside the reading of standard output in the main thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM