C# 执行CMD命令

<pre name="code" class="csharp">using System;
using System.Diagnostics;

namespace ConsoleApplication9
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(ExeCommand("dir"));
        }

        #region 执行cmd命令  

        /// <summary>  
        /// 执行cmd命令  
        /// </summary>  
        /// <param name="commandText"></param>  
        /// <returns></returns>  
        private static string ExeCommand(string commandText)
        {
            Process p = new Process();  //创建并实例化一个操作进程的类:Process  
            p.StartInfo.FileName = "cmd.exe";    //设置要启动的应用程序  
            p.StartInfo.UseShellExecute = false;   //设置是否使用操作系统shell启动进程  
            p.StartInfo.RedirectStandardInput = true;  //指示应用程序是否从StandardInput流中读取  
            p.StartInfo.RedirectStandardOutput = true; //将应用程序的输入写入到StandardOutput流中  
            p.StartInfo.RedirectStandardError = true;  //将应用程序的错误输出写入到StandarError流中  
            p.StartInfo.CreateNoWindow = true;    //是否在新窗口中启动进程  
            string strOutput = null;
            try
            {
                p.Start();
                p.StandardInput.WriteLine(commandText);    //将CMD命令写入StandardInput流中  
                p.StandardInput.WriteLine("exit");         //将 exit 命令写入StandardInput流中  
                strOutput = p.StandardOutput.ReadToEnd();   //读取所有输出的流的所有字符  
                p.WaitForExit();                           //无限期等待,直至进程退出  
                p.Close();                                  //释放进程,关闭进程  
            }
            catch (Exception e)
            {
                strOutput = e.Message;
            }
            return strOutput;
        }
        #endregion
    }
}



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值