Monday, 27 April 2009

Run System Process without showing Command Window and get an output

In this post I would like to show the sample code on how to start a process without showing a console window and get an output result. I am going to use System.Diagnostics.Process class and set parameters to it. Function below will execute a specified command with parameters and return an output on successful run or nothing if there was an error.

using using System.Diagnostics;
private static string RunProcess(string command, string parameters)
    string output = string.Empty;

        Process process = new Process();
        process.StartInfo.CreateNoWindow = true;    // Don't create command window
        process.StartInfo.FileName = command;
        process.StartInfo.Arguments = parameters;
        process.StartInfo.UseShellExecute = false;  // Don't use system shell for execution 
        process.StartInfo.RedirectStandardOutput = true;    // Give us an output
        process.StartInfo.RedirectStandardError = true;     // Give us an error output
        bool r = process.Start();

        StreamReader streamReader = process.StandardOutput;
        // Read the standard output of the spawned process.
        output = streamReader.ReadLine();
        if (output == null)
            StreamReader errorStream = process.StandardError;
            string error = errorStream.ReadToEnd();


    return output;

This function can be modified to return an error output in exception or logged into file.

No comments:

Post a Comment