永发信息网

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

答案:5  悬赏:10  手机版
解决时间 2021-04-06 08:14
  • 提问者网友:你独家记忆
  • 2021-04-05 08:21
怎么在C#里运行命令行里的命令?
最佳答案
  • 五星知识达人网友:行路难
  • 2021-04-05 08:33
首先,我们用使用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();
全部回答
  • 1楼网友:春色三分
  • 2021-04-05 11:25
你问的不明白!
  • 2楼网友:十年萤火照君眠
  • 2021-04-05 11:18
给你个方法
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; /
}
  • 3楼网友:蕴藏春秋
  • 2021-04-05 10:07
你是说数据库吗?如果是的话可以(以ACCESS数据库为例):
string conStr="provider=Microsoft.jet.oledb.4.0,datasource="sample.mdb"
oledbConnection con=new oledbConnection(conStr);
OleDbCommand cmd= new OleDbCommand("select * from tableName", con);
OleDbDataAdapter ad = new OleDbDataAdapter(cmd);
dataset ds=new dataset();
ad.fill(ds,tableName);//将tableName表中的所有数据填充到ds中
若是要执行CMD的话,
如非查询:cmd.excuteNonQuery();
  • 4楼网友:西岸风
  • 2021-04-05 09:40
将代码写在文本文件中,然后保持为.bat文件,再打开就执行了.
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯