怎么在C#里运行命令行里的命令?

[复制链接]
查看11 | 回复3 | 2010-4-17 17:06:43 | 显示全部楼层 |阅读模式
给你个方法using System.Diagnostics; private string RunCmd(string command, int milliseconds)
{
Process p = new Process();
string res = string.Empty;p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c " + command;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
try
{
if (p.Start())
//开始进程
{
if (milliseconds == 0)
p.WaitForExit();
//这里无限等待进程结束
else
p.WaitForExit(milliseconds);//这里等待进程结束,等待时间为指定的毫秒
res = p.StandardOutput.ReadToEnd();
}
}
catch
{
}
finally
{
if (p != null)
p.Close();
KillProcess(p);
}
return res;
/
}
回复

使用道具 举报

千问 | 2010-4-17 17:06:43 | 显示全部楼层
将代码写在文本文件中,然后保持为.bat文件,再打开就执行了.
回复

使用道具 举报

千问 | 2010-4-17 17:06:43 | 显示全部楼层
首先,我们用使用Process类,来创建独立的进程,导入System.Diagnostics,using System.Diagnostics;实例一个Process类,启动一个独立进程Process p = new Process();Process类有一个StartInfo属性,这个是ProcessStartInfo类,包括了一些属性和方法,下面我们用到了他的几个属性:设定程序名p.StartInfo.FileName = "cmd.exe";关闭Shell的使用p.StartInfo.UseShellExecute = false;重定向标准输入p.StartInfo.RedirectStandardInput = true;重定向标准输出p.StartInfo.RedirectStandardOutput = true;重定向错误输出p.StartInfo.RedirectStandardError = true;设置不显示窗口p.StartInfo.CreateNoWindow = true;上面几个属性的设置是比较关键的一步。既然都设置好了那就启动进程吧,p.Start();输入要执行的命令p.StandardInput.WriteLine("/*指令*/");p.StandardInput.WriteLine("exit");从输出流获取命令执行结果,string strRst = p.StandardOutput.ReadToEnd();
回复

使用道具 举报

千问 | 2010-4-17 17:06:43 | 显示全部楼层
你问的不明白!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行