Wednesday, November 11, 2009

Execute CMD command on ASP.NET App

Hello guys, this time I spent one full day digging my way into this one..
The main question here is: How can I execute a command or a list of commands as if I where on the command prompt, and get the response?

I can give you right now the answer! (after banging my head over and over on the keyboard for one day...)

public static string ExecuteCmdCommands(List< string > commands)
        {
            Process p = new Process();
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.FileName = @"cmd";
            p.StartInfo.UseShellExecute = false;
            p.Start();

            StreamWriter sIn = p.StandardInput;
            sIn.AutoFlush = true;

            StreamReader sOut = p.StandardOutput;

            for (int i = 0; i <= commands.Count - 1; i++)
            {
                sIn.Write(commands[i] + System.Environment.NewLine);
            }
            
            sIn.Close();
            string result = sOut.ReadToEnd().Trim();
            p.Close();

            return result;
        }

How simple is it? You just create a Process, set the RedirectStandardOutput and RedirectStandardInput to true, so you can create a Stream for reading and writing to/from that process, the FileName is the prompt itself and the UseShellExecute is a pre requisite.
Then start writing out your instructions to the command prompt, always followed by a Environment.NewLine (simulate a Return) and afterwards, you get the output on the reader Stream, that simple!

And, you don't need to change any permissions on the user executing your worker process or app pool for your application, which is great so you don't create any security holes on your web server.

Hopefully this will save you hours, like it would if I had this before!

See you soon

No comments: