C#中隐式操作CMD命令行窗口 (转)

MS的CMD命令行是一种重要的操作界面,一些在C#中不那么方便完成的功能,在CMD中几个简单的命令或许就可以轻松搞定,如果能在C#中能完成CMD窗口的功能,那一定可以使我们的程序简便不少。

下面介绍一种常用的在C#程序中调用CMD.exe程序,并且不显示命令行窗口界面,来完成CMD中各种功能的简单方法。

如下所示:

System.Diagnosties.Process p=new 
System.Diagnosties.Process();
p.StartInfo.FileName="cmd.exe";//要执行的程序名称
p.StartInfo.UseShellExecute=false;
p.StartInfo.RedirectStanderInput=true;//可能接受来自调用程序的输入信息
p.StartInfo.RedirectStanderOutput=true;//由调用程序获取输出信息
p.StartInfo.CreateNoWindow=true;//不显示程序窗口
p.Start();//启动程序
//向CMD窗口发送输入信息:
p.StanderInput.WriteLine("shutdown 
-r t 10"); //10秒后重启(C#中可不好做哦)
//获取CMD窗口的输出信息:
string sOutput = 
p.StandardOutput.ReadToEnd();有啦以下代码,就可以神不知鬼不觉的操作CMD啦。总之,Process类是一个非常有用的类,它十分方便的利用第三方的程序扩展了C#的功能。

最好的实现方式是使用事件:

  // some of the flags are not needed
    process
.StartInfo.CreateNoWindow = true;
    process
.StartInfo.ErrorDialog = false;
    process
.StartInfo.UseShellExecute = false;
    process
.StartInfo.RedirectStandardError = true;
    process
.StartInfo.RedirectStandardInput = true;
    process
.StartInfo.RedirectStandardOutput = true;
    process
.EnableRaisingEvents = true;
    process
.OutputDataReceived += process_OutputDataReceived;
    process
.ErrorDataReceived += process_OutputDataReceived;
    process
.Exited += process_Exited;
    process
.Start();
    process
.BeginErrorReadLine();
    process
.BeginOutputReadLine();

   
void process_Exited(object sender, System.EventArgs e)
   
{
       
// do something when process terminates;
   
}

   
void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
   
{
       
// a line is writen to the out stream. you can use it like:
       
string s = e.Data;
   
}

   
void process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
   
{
       
// a line is writen to the out stream. you can use it like:
       
string s = e.Data;
   
}

c#执行shell

        private void Form1_Load(object sender, EventArgs e)

        {

            //实例一个process类

            Process process = new Process();

            //设定程序名

            process.StartInfo.FileName = "cmd.exe";

            //关闭Shell的使用

            process.StartInfo.UseShellExecute = false;

            //重新定向标准输入,输入,错误输出

            process.StartInfo.RedirectStandardInput = true;

            process.StartInfo.RedirectStandardOutput = true;

            process.StartInfo.RedirectStandardError = true;

            //设置cmd窗口不显示

            process.StartInfo.CreateNoWindow = true;

            //开始

            process.Start();

            //输入命令,退出

            process.StandardInput.WriteLine("ping 192.168.0.1");

            //process.StandardInput.WriteLine("netstat");

            process.StandardInput.WriteLine("exit");

            //获取结果

            string strRst = process.StandardOutput.ReadToEnd();

            //显示结果到RichTextBox

            this.richTextBox1.Text = strRst;

        }

线程重定向问题

描叙:打开cmd窗口,进入要编译的目录的d:linuxcase_3,在cmd窗口打开grads程序,在grads程序中执行out.gs,退出grads,退出cmd
编译错误:未重定向
  private void Form1_Load(object sender, EventArgs e)
         {

             //实例一个process类
             Process process = new Process();
             //设定程序名
             process.StartInfo.FileName = "cmd.exe";
             //关闭Shell的使用
             process.StartInfo.UseShellExecute = false;
             //重新定向标准输入,输入,错误输出
             process.StartInfo.RedirectStandardInput = true;
             process.StartInfo.RedirectStandardOutput = true;
             process.StartInfo.RedirectStandardError = true;
             //设置cmd窗口不显示
             process.StartInfo.CreateNoWindow = false;
             //开始
             process.Start();
             //输入命令,退出
             process.StandardInput.WriteLine(@"cd d:linuxcase_3");
             //在cmd中打开grads程序,在进程中产生grads.exe
             process.StandardInput.WriteLine("grads");
             process.StandardInput.WriteLine("y");


             bool isIniit = true;
             Process processTemp;
             while (isIniit)
             {
                 Process[] processeszu = System.Diagnostics.Process.GetProcesses();//获取系统进程

                 string processnamelist = string.Empty;
                 for (int i = 0; i < processeszu.Length - 1; i++)
                 {
                     processTemp = processeszu;
                     if (processTemp.ProcessName == "Grads")//判断Grads这个进程是否打开
                     {
                 processTemp.StartInfo.RedirectStandardInput = true;
                 processTemp.StandardInput.WriteLine(@"out.gs");
                 processTemp.StandardInput.WriteLine("quit");
                       isIniit = false;
                         break;
                     }

                 }
             }
      
               
                 process.StandardInput.WriteLine("exit");
          
             //获取结果

             //显示结果到RichTextBox
             this.richTextBox1.Text = process.StandardOutput.ReadToEnd();
         }

Process类详细介绍

//启动浏览器,并打开指定的地址
None.gif
            string ipAddress = "127.0.0.1";
None.gif            
try
ExpandedBlockStart.gif            
{
InBlock.gif                IPHostEntry ipHost 
= Dns.Resolve(Dns.GetHostName());
InBlock.gif                ipAddress 
= ipHost.AddressList[0].ToString().Trim();
ExpandedBlockEnd.gif            }

None.gif            
catch (Exception)
ExpandedBlockStart.gif            

ExpandedBlockEnd.gif            }

None.gif            
None.gif
None.gif            Process p 
= new Process();
None.gif            p.StartInfo.FileName 
= "iexplore.exe";
None.gif            p.StartInfo.Arguments 
= "http://" + ipAddress + "/WebFinanceAllowance/";
None.gif            p.Start();
None.gif            p.Close();
None.gif
None.gif
None.gif            
//关闭打开的进程
None.gif
            if (!p.HasExited)
ExpandedBlockStart.gif            
{
InBlock.gif                p.CloseMainWindow();
ExpandedBlockEnd.gif            }

1 None.gif // 启动资源管理器,并打开指定路径
2 None.gif             Process.Start( " explorer.exe " , "C:\\ mysql " );
None.gif // 使用process类来执行dos命令
None.gif
                Process process  =   new  Process();
None.gif                process.StartInfo.FileName 
=   " cmd.exe " ;
None.gif                process.StartInfo.UseShellExecute 
=   false ;
None.gif                process.StartInfo.RedirectStandardInput 
=   true ;
None.gif                process.StartInfo.RedirectStandardOutput 
=   true ;
None.gif                process.StartInfo.RedirectStandardError 
=   true ;
None.gif                process.StartInfo.CreateNoWindow 
=   true ;
None.gif
None.gif               
None.gif
None.gif                
// 开始卸载
None.gif
                process.Start();
None.gif                process.StandardInput.WriteLine(
" cd C:\\mysql\\bin " );
None.gif                process.StandardInput.WriteLine(
" net stop mysql " );
None.gif                process.StandardInput.WriteLine(
" mysqld -remove " );
None.gif                process.StandardInput.WriteLine(
" exit " );
None.gif                process.Close();
None.gif                
// 卸载完毕
 1 None.gif   // 用msiexec.exe执行一个安装程序
 2 None.gif                  string  fileName  =  setupPath  +   " Installer.msi " ;
 3 None.gif                Process p  =   new  Process();
 4 None.gif                p.StartInfo.FileName  =   " msiexec.exe " ;
 5 None.gif                p.StartInfo.Arguments  =   string .Format( "  /i {0} /passive " , fileName);
 6 None.gif                p.StartInfo.UseShellExecute  =   false ;
 7 None.gif                p.StartInfo.RedirectStandardInput  =   true ;
 8 None.gif                p.StartInfo.RedirectStandardOutput  =   true ;
 9 None.gif                p.StartInfo.CreateNoWindow  =   false ;
10 None.gif                p.Start();

转载于:https://www.cnblogs.com/Tammie/archive/2011/09/06/2168335.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值