Brian Clifton . com

Shell Execute with output in C#

Posted by Brian Clifton
Written July 31, 2008 at 01:03
Using the System.Diagnostics.Process class you can get a stream to read the output of the application you are executing. For example, you could execute "dir" to list get the directory contents of the working directory specified as a string.

Here's a basic class I wrote that allows you to get the standard output:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;

class WindowsHelper{
    public static string ShellExecute(string dir,string file,string args)
    {
        Process p = new System.Diagnostics.Process();
        p.StartInfo.WorkingDirectory = dir;
        p.StartInfo.FileName = file;
        p.StartInfo.Verb = "open";
        p.StartInfo.Arguments = args;

        //required to capture standard output
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.UseShellExecute = false;
        p.Start();
        p.WaitForExit();

        //read the command line output
        StreamReader sr = p.StandardOutput;
        return(sr.ReadToEnd());
    }
}

 

© Brian Clifton. All rights reserved.