C # execute command cmd

  • CMD's proxy, etc. set, the environment variable information sharing operating system configuration
  • Note that exception handling, recycling process
  • The following are disadvantages to achieve, the string returned redundant data, such as the open operating environment information when the CMD, therefore you may want to go their own filtering out what is the command returns data
  • Regardless of whether the command was successfully executed an exit command or when calling ReadToEnd () method, will be in a state of suspended animation
    /// <summary>
    /// 
    /// </summary>
    public class Cmd
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="cmd"></param>
        public static string RunCmd(string cmd)
        {
            using (Process proc = new Process())
            {
                proc.StartInfo.CreateNoWindow = true;
                proc.StartInfo.FileName = "cmd.exe";
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardError = true;
                proc.StartInfo.RedirectStandardInput = true;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.Start();
                proc.StandardInput.WriteLine(cmd);
                proc.StandardInput.WriteLine("exit");
                string outStr = proc.StandardOutput.ReadToEnd();
                proc.Close();
                return outStr;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="programName"></param>
        /// <param name="cmd"></param>
        public static void RunProgram(string programName, string cmd)
        {
            using (Process proc = new Process())
            {
                proc.StartInfo.CreateNoWindow = true;
                proc.StartInfo.FileName = programName;
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardError = true;
                proc.StartInfo.RedirectStandardInput = true;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.Start();
                if (cmd.Length != 0)
                {
                    proc.StandardInput.WriteLine(cmd);
                }
                proc.Close();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="programName"></param>
        public static void RunProgram(string programName)
        {
            RunProgram(programName, "");
        }
    }

Guess you like

Origin www.cnblogs.com/wyp1988/p/11388622.html