July 1, 2010

Start a Process and Capture the Output in c#

Simple sample for running a process synchronously and capturing the output
public string GetEnvironmentVars()
{
    Process process = new Process();
    // UseShellExecute must be 'false' when redirecting the output
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    process.StartInfo.CreateNoWindow = true;
    process.StartInfo.FileName = "p4";
    process.StartInfo.Arguments = " set ";
    //process.StartInfo.WorkingDirectory = dir;
    process.Start();
    string output = process.StandardOutput.ReadToEnd();
    //string error = process.StandardError.ReadToEnd();
    // Wait a reasonable ammount of time for it to finish
    bool res = process.WaitForExit(5000); 
    return res ? output : "Command \"" + 
        process.StartInfo.FileName + process.StartInfo.Arguments +
        "\" failed to exit:" + Environment.NewLine + output;
}

No comments: