使用C#调用外部序或是执行DOS命令

使用 System.Diagnostics.Process.Start();

:System.Diagnostics.Process.Start("abc.txt");

.net里,提供了Process类,提供我们强大的调用外部工具功能,并透过重新导向输入与输出,可以取得执行结果,下面就用一个例子来示范在一个WinForm里输入一个Dos命令,然后呼叫CMD.EXE来执行,并取回执行的结果。



private string RunCmd(string command)
{
//
实例一个Process类,启动一个独立进程

Process p = new Process();


//Process类有一个StartInfo属性,这个是ProcessStartInfo类,包括了一些属性和方法,下面我们用到了他的几个属性:


p.StartInfo.FileName = "cmd.exe"; //设定程序名

p.StartInfo.Arguments = "/c " + command; //设定程序执行参数

p.StartInfo.UseShellExecute = false; //关闭Shell的使用

p.StartInfo.RedirectStandardInput = true; //复位向标准输入

p.StartInfo.RedirectStandardOutput = true; //复位向标准输出

p.StartInfo.RedirectStandardError = true; //复位向错误输出

p.StartInfo.CreateNoWindow = true; //设置不显示窗口

p.Start(); //启动

//p.StandardInput.WriteLine(command); //也可以用这种方式输入要执行的命令

//p.StandardInput.WriteLine("exit"); //不过要记得加上Exit要不然下一行程序执行的时候会当机

return p.StandardOutput.ReadToEnd(); //从输出流取得命令执行结果

}

posted @ 2007-05-16 10:23  Yoshow  阅读(698)  评论(0)    收藏  举报