敬业的IT人 >> 操作系统 >> 其他操作系 >> C#中利用process类调用外部程序以及执行dos命令

C#中利用process类调用外部程序以及执行dos命令

敬业的IT人 互联网 佚名 2008-1-3 9:46:16

c#中的Process类可方便的调用外部程序,所以我们可以通过调用cmd.exe程序

加入参数 "/c " + 要执行的命令来执行一个dos命令
(/c代表执行参数指定的命令后关闭cmd.exe /k参数则不关闭cmd.exe)

 1         private string RunCmd(string command)
     2         {
 3             //实例一个Process类,启动一个独立进程
 4             Process p = new Process();
 5
 6             //Process类有一个StartInfo属性,这个是ProcessStartInfo类,包括了一些属性和方法,下面我们用到了他的几个属性:
 7
 8             p.StartInfo.FileName = "cmd.exe";           //设定程序名
 9             p.StartInfo.Arguments = "/c " + command;    //设定程式执行参数
10             p.StartInfo.UseShellExecute = false;        //关闭Shell的使用
11             p.StartInfo.RedirectStandardInput = true;   //重定向标准输入
12             p.StartInfo.RedirectStandardOutput = true;  //重定向标准输出
13             p.StartInfo.RedirectStandardError = true;   //重定向错误输出
14             p.StartInfo.CreateNoWindow = true;          //设置不显示窗口
15
16             p.Start();   //启动
17            
18             //p.StandardInput.WriteLine(command);       //也可以用这种方式输入要执行的命令
19             //p.StandardInput.WriteLine("exit");        //不过要记得加上Exit要不然下一行程式执行的时候会当机
20            
21             return p.StandardOutput.ReadToEnd();        //从输出流取得命令执行结果
22
23         }

巧巧读书:进入讨论组讨论。
粤ICP备06119539号
Copyright CiscoSky.Org,Some Rights Reserved.
Email:me1228#tom.com