http://www.csdn.net/Develop/read_article.asp?id=25900

解决方案 »

  1.   

    /// <summary>
    /// 执行单条命令
    /// </summary>
    /// <param name="commandText">命令文本</param>
    /// <returns>命令输出文本</returns>
    public static string ExeCommand(string commandText)
    {
    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();
    p.StandardInput.WriteLine(commandText);
    p.StandardInput.WriteLine("exit");
    //string formats = s.Replace("\r","").Replace("\n","\r\n");
    strOutput = p.StandardOutput.ReadToEnd();
    p.WaitForExit();
    p.Close();
    }
    catch(Exception e)
    {
    strOutput = e.Message;
    }
    return strOutput;
    }
    /// <summary>
    /// 执行多条命令
    /// </summary>
    /// <param name="commandArray">命令文本数组</param>
    /// <returns>命令输出文本</returns>
    public static string ExeCommand(string [] commandTexts)
    {
    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();
    p.WaitForExit();
    p.Close();
    }
    catch(Exception e)
    {
    strOutput = e.Message;
    }
    return strOutput;
    }
      

  2.   

    补充:
    最好用System.Environment.GetEnvironmentVariable("comspec")来获得cmd.exe或command.com的路径。