Execute shell Command - CSharp System.Diagnostics

CSharp examples for System.Diagnostics:Process

Description

Execute shell Command

Demo Code


using System.Diagnostics;

public class Main{

        public static string ExeCommand(string[] commandTexts)
        {/*ww w  .j  a  v  a 2 s  . c  om*/
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            string strOutput = null;
            try
            {
                p.Start();
                foreach (string item in commandTexts)
                {
                    p.StandardInput.WriteLine(item);
                }
                p.StandardInput.WriteLine("exit");
                strOutput = p.StandardOutput.ReadToEnd();
                //strOutput = Encoding.UTF8.GetString(Encoding.Default.GetBytes(strOutput));
                p.WaitForExit();
                p.Close();
            }
            catch (Exception e)
            {
                strOutput = e.Message;
            }
            return strOutput;
        }

        public static string ExeCommand(string commandText)
        {
            return ExeCommand(new string[] { commandText });
        }
}

Related Tutorials