您的位置:首页 > 编程语言 > C#

C#中隐式运行CMD命令行窗口的方法

2017-03-27 19:02 344 查看
using System;
using System.Diagnostics;
namespace Business
{
/// <summary>
/// Command 的摘要说明。
/// </summary>
public class Command
{
private Process proc = null;
/// <summary>
/// 构造方法
/// </summary>
public Command()
{
proc = new Process();
}
/// <summary>
/// 执行CMD语句
/// </summary>
/// <param name="cmd">要执行的CMD命令</param>
public void RunCmd(string cmd)
{
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
proc.StandardInput.WriteLine(cmd);
proc.Close();
}
/// <summary>
/// 打开软件并执行命令
/// </summary>
/// <param name="programName">软件路径加名称(.exe文件)</param>
/// <param name="cmd">要执行的命令</param>
public void RunProgram(string programName,string 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#的功能。

if (cmd.Length != 0)
{
proc.StandardInput.WriteLine(cmd);
}
proc.Close();
}
/// <summary>
/// 打开软件
/// </summary>
/// <param name="programName">软件路径加名称(.exe文件)</param>
public void RunProgram(string programName)
{
this.RunProgram(programName,"");
}
}
}


调用时

Command cmd = new Command();
cmd.RunCmd("dir");


获取输出信息应注意:

ReadtoEnd()容易卡住:

string outStr = proc.StandardOutput.ReadtoEnd();


更倾向于使用ReadLine():

[csharp] view plaincopyprint?string tmptStr = proc.StandardOutput.ReadLine();
string outStr = "";
while (tmptStr != "")
{
outStr += outStr;
tmptStr = proc.StandardOutput.ReadLine();
}


调用第三方exe时可以使用如下:

/// <summary>
/// 执行ThermSpy.exe
/// </summary>
private void CmdThermSpy()
{
Process p = new Process();
p.StartInfo.WorkingDirectory = Environment.CurrentDirectory;
p.StartInfo.FileName = "ThermSpyPremium.exe";
p.StartInfo.Arguments = "-header:gpu -datetime -log:NV_clock.log";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: